babylon.max.js 4.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106931079310893109931109311193112931139311493115931169311793118931199312093121931229312393124931259312693127931289312993130931319313293133931349313593136931379313893139931409314193142931439314493145931469314793148931499315093151931529315393154931559315693157931589315993160931619316293163931649316593166931679316893169931709317193172931739317493175931769317793178931799318093181931829318393184931859318693187931889318993190931919319293193931949319593196931979319893199932009320193202932039320493205932069320793208932099321093211932129321393214932159321693217932189321993220932219322293223932249322593226932279322893229932309323193232932339323493235932369323793238932399324093241932429324393244932459324693247932489324993250932519325293253932549325593256932579325893259932609326193262932639326493265932669326793268932699327093271932729327393274932759327693277932789327993280932819328293283932849328593286932879328893289932909329193292932939329493295932969329793298932999330093301933029330393304933059330693307933089330993310933119331293313933149331593316933179331893319933209332193322933239332493325933269332793328933299333093331933329333393334933359333693337933389333993340933419334293343933449334593346933479334893349933509335193352933539335493355933569335793358933599336093361933629336393364933659336693367933689336993370933719337293373933749337593376933779337893379933809338193382933839338493385933869338793388933899339093391933929339393394933959339693397933989339993400934019340293403934049340593406934079340893409934109341193412934139341493415934169341793418934199342093421934229342393424934259342693427934289342993430934319343293433934349343593436934379343893439934409344193442934439344493445934469344793448934499345093451934529345393454934559345693457934589345993460934619346293463934649346593466934679346893469934709347193472934739347493475934769347793478934799348093481934829348393484934859348693487934889348993490934919349293493934949349593496934979349893499935009350193502935039350493505935069350793508935099351093511935129351393514935159351693517935189351993520935219352293523935249352593526935279352893529935309353193532935339353493535935369353793538935399354093541935429354393544935459354693547935489354993550935519355293553935549355593556935579355893559935609356193562935639356493565935669356793568935699357093571935729357393574935759357693577935789357993580935819358293583935849358593586935879358893589935909359193592935939359493595935969359793598935999360093601936029360393604936059360693607936089360993610936119361293613936149361593616936179361893619936209362193622936239362493625936269362793628936299363093631936329363393634936359363693637936389363993640936419364293643936449364593646936479364893649936509365193652936539365493655936569365793658936599366093661936629366393664936659366693667936689366993670936719367293673936749367593676936779367893679936809368193682936839368493685936869368793688936899369093691936929369393694936959369693697936989369993700937019370293703937049370593706937079370893709937109371193712937139371493715937169371793718937199372093721937229372393724937259372693727937289372993730937319373293733937349373593736937379373893739937409374193742937439374493745937469374793748937499375093751937529375393754937559375693757937589375993760937619376293763937649376593766937679376893769937709377193772937739377493775937769377793778937799378093781937829378393784937859378693787937889378993790937919379293793937949379593796937979379893799938009380193802938039380493805938069380793808938099381093811938129381393814938159381693817938189381993820938219382293823938249382593826938279382893829938309383193832938339383493835938369383793838938399384093841938429384393844938459384693847938489384993850938519385293853938549385593856938579385893859938609386193862938639386493865938669386793868938699387093871938729387393874938759387693877938789387993880938819388293883938849388593886938879388893889938909389193892938939389493895938969389793898938999390093901939029390393904939059390693907939089390993910939119391293913939149391593916939179391893919939209392193922939239392493925939269392793928939299393093931939329393393934939359393693937939389393993940939419394293943939449394593946939479394893949939509395193952939539395493955939569395793958939599396093961939629396393964939659396693967939689396993970939719397293973939749397593976939779397893979939809398193982939839398493985939869398793988939899399093991939929399393994939959399693997939989399994000940019400294003940049400594006940079400894009940109401194012940139401494015940169401794018940199402094021940229402394024940259402694027940289402994030940319403294033940349403594036940379403894039940409404194042940439404494045940469404794048940499405094051940529405394054940559405694057940589405994060940619406294063940649406594066940679406894069940709407194072940739407494075940769407794078940799408094081940829408394084940859408694087940889408994090940919409294093940949409594096940979409894099941009410194102941039410494105941069410794108941099411094111941129411394114941159411694117941189411994120941219412294123941249412594126941279412894129941309413194132941339413494135941369413794138941399414094141941429414394144941459414694147941489414994150941519415294153941549415594156941579415894159941609416194162941639416494165941669416794168941699417094171941729417394174941759417694177941789417994180941819418294183941849418594186941879418894189941909419194192941939419494195941969419794198941999420094201942029420394204942059420694207942089420994210942119421294213942149421594216942179421894219942209422194222942239422494225942269422794228942299423094231942329423394234942359423694237942389423994240942419424294243942449424594246942479424894249942509425194252942539425494255942569425794258942599426094261942629426394264942659426694267942689426994270942719427294273942749427594276942779427894279942809428194282942839428494285942869428794288942899429094291942929429394294942959429694297942989429994300943019430294303943049430594306943079430894309943109431194312943139431494315943169431794318943199432094321943229432394324943259432694327943289432994330943319433294333943349433594336943379433894339943409434194342943439434494345943469434794348943499435094351943529435394354943559435694357943589435994360943619436294363943649436594366943679436894369943709437194372943739437494375943769437794378943799438094381943829438394384943859438694387943889438994390943919439294393943949439594396943979439894399944009440194402944039440494405944069440794408944099441094411944129441394414944159441694417944189441994420944219442294423944249442594426944279442894429944309443194432944339443494435944369443794438944399444094441944429444394444944459444694447944489444994450944519445294453944549445594456944579445894459944609446194462944639446494465944669446794468944699447094471944729447394474944759447694477944789447994480944819448294483944849448594486944879448894489944909449194492944939449494495944969449794498944999450094501945029450394504945059450694507945089450994510945119451294513945149451594516945179451894519945209452194522945239452494525945269452794528945299453094531945329453394534945359453694537945389453994540945419454294543945449454594546945479454894549945509455194552945539455494555945569455794558945599456094561945629456394564945659456694567945689456994570945719457294573945749457594576945779457894579945809458194582945839458494585945869458794588945899459094591945929459394594945959459694597945989459994600946019460294603946049460594606946079460894609946109461194612946139461494615946169461794618946199462094621946229462394624946259462694627946289462994630946319463294633946349463594636946379463894639946409464194642946439464494645946469464794648946499465094651946529465394654946559465694657946589465994660946619466294663946649466594666946679466894669946709467194672946739467494675946769467794678946799468094681946829468394684946859468694687946889468994690946919469294693946949469594696946979469894699947009470194702947039470494705947069470794708947099471094711947129471394714947159471694717947189471994720947219472294723947249472594726947279472894729947309473194732947339473494735947369473794738947399474094741947429474394744947459474694747947489474994750947519475294753947549475594756947579475894759947609476194762947639476494765947669476794768947699477094771947729477394774947759477694777947789477994780947819478294783947849478594786947879478894789947909479194792947939479494795947969479794798947999480094801948029480394804948059480694807948089480994810948119481294813948149481594816948179481894819948209482194822948239482494825948269482794828948299483094831948329483394834948359483694837948389483994840948419484294843948449484594846948479484894849948509485194852948539485494855948569485794858948599486094861948629486394864948659486694867948689486994870948719487294873948749487594876948779487894879948809488194882948839488494885948869488794888948899489094891948929489394894948959489694897948989489994900949019490294903949049490594906949079490894909949109491194912949139491494915949169491794918949199492094921949229492394924949259492694927949289492994930949319493294933949349493594936949379493894939949409494194942949439494494945949469494794948949499495094951949529495394954949559495694957949589495994960949619496294963949649496594966949679496894969949709497194972949739497494975949769497794978949799498094981949829498394984949859498694987949889498994990949919499294993949949499594996949979499894999950009500195002950039500495005950069500795008950099501095011950129501395014950159501695017950189501995020950219502295023950249502595026950279502895029950309503195032950339503495035950369503795038950399504095041950429504395044950459504695047950489504995050950519505295053950549505595056950579505895059950609506195062950639506495065950669506795068950699507095071950729507395074950759507695077950789507995080950819508295083950849508595086950879508895089950909509195092950939509495095950969509795098950999510095101951029510395104951059510695107951089510995110951119511295113951149511595116951179511895119951209512195122951239512495125951269512795128951299513095131951329513395134951359513695137951389513995140951419514295143951449514595146951479514895149951509515195152951539515495155951569515795158951599516095161951629516395164951659516695167951689516995170951719517295173951749517595176951779517895179951809518195182951839518495185951869518795188951899519095191951929519395194951959519695197951989519995200952019520295203952049520595206952079520895209952109521195212952139521495215952169521795218952199522095221952229522395224952259522695227952289522995230952319523295233952349523595236952379523895239952409524195242952439524495245952469524795248952499525095251952529525395254952559525695257952589525995260952619526295263952649526595266952679526895269952709527195272952739527495275952769527795278952799528095281952829528395284952859528695287952889528995290952919529295293952949529595296952979529895299953009530195302953039530495305953069530795308953099531095311953129531395314953159531695317953189531995320953219532295323953249532595326953279532895329953309533195332953339533495335953369533795338953399534095341953429534395344953459534695347953489534995350953519535295353953549535595356953579535895359953609536195362953639536495365953669536795368953699537095371953729537395374953759537695377953789537995380953819538295383953849538595386953879538895389953909539195392953939539495395953969539795398953999540095401954029540395404954059540695407954089540995410954119541295413954149541595416954179541895419954209542195422954239542495425954269542795428954299543095431954329543395434954359543695437954389543995440954419544295443954449544595446954479544895449954509545195452954539545495455954569545795458954599546095461954629546395464954659546695467954689546995470954719547295473954749547595476954779547895479954809548195482954839548495485954869548795488954899549095491954929549395494954959549695497954989549995500955019550295503955049550595506955079550895509955109551195512955139551495515955169551795518955199552095521955229552395524955259552695527955289552995530955319553295533955349553595536955379553895539955409554195542955439554495545955469554795548955499555095551955529555395554955559555695557955589555995560955619556295563955649556595566955679556895569955709557195572955739557495575955769557795578955799558095581955829558395584955859558695587955889558995590955919559295593955949559595596955979559895599956009560195602956039560495605956069560795608956099561095611956129561395614956159561695617956189561995620956219562295623956249562595626956279562895629956309563195632956339563495635956369563795638956399564095641956429564395644956459564695647956489564995650956519565295653956549565595656956579565895659956609566195662956639566495665956669566795668956699567095671956729567395674956759567695677956789567995680956819568295683956849568595686956879568895689956909569195692956939569495695956969569795698956999570095701957029570395704957059570695707957089570995710957119571295713957149571595716957179571895719957209572195722957239572495725957269572795728957299573095731957329573395734957359573695737957389573995740957419574295743957449574595746957479574895749957509575195752957539575495755957569575795758957599576095761957629576395764957659576695767957689576995770957719577295773957749577595776957779577895779957809578195782957839578495785957869578795788957899579095791957929579395794957959579695797957989579995800958019580295803958049580595806958079580895809958109581195812958139581495815958169581795818958199582095821958229582395824958259582695827958289582995830958319583295833958349583595836958379583895839958409584195842958439584495845958469584795848958499585095851958529585395854958559585695857958589585995860958619586295863958649586595866958679586895869958709587195872958739587495875958769587795878958799588095881958829588395884958859588695887958889588995890958919589295893958949589595896958979589895899959009590195902959039590495905959069590795908959099591095911959129591395914959159591695917959189591995920959219592295923959249592595926959279592895929959309593195932959339593495935959369593795938959399594095941959429594395944959459594695947959489594995950959519595295953959549595595956959579595895959959609596195962959639596495965959669596795968959699597095971959729597395974959759597695977959789597995980959819598295983959849598595986959879598895989959909599195992959939599495995959969599795998959999600096001960029600396004960059600696007960089600996010960119601296013960149601596016960179601896019960209602196022960239602496025960269602796028960299603096031960329603396034960359603696037960389603996040960419604296043960449604596046960479604896049960509605196052960539605496055960569605796058960599606096061960629606396064960659606696067960689606996070960719607296073960749607596076960779607896079960809608196082960839608496085960869608796088960899609096091960929609396094960959609696097960989609996100961019610296103961049610596106961079610896109961109611196112961139611496115961169611796118961199612096121961229612396124961259612696127961289612996130961319613296133961349613596136961379613896139961409614196142961439614496145961469614796148961499615096151961529615396154961559615696157961589615996160961619616296163961649616596166961679616896169961709617196172961739617496175961769617796178961799618096181961829618396184961859618696187961889618996190961919619296193961949619596196961979619896199962009620196202962039620496205962069620796208962099621096211962129621396214962159621696217962189621996220962219622296223962249622596226962279622896229962309623196232962339623496235962369623796238962399624096241962429624396244962459624696247962489624996250962519625296253962549625596256962579625896259962609626196262962639626496265962669626796268962699627096271962729627396274962759627696277962789627996280962819628296283962849628596286962879628896289962909629196292962939629496295962969629796298962999630096301963029630396304963059630696307963089630996310963119631296313963149631596316963179631896319963209632196322963239632496325963269632796328963299633096331963329633396334963359633696337963389633996340963419634296343963449634596346963479634896349963509635196352963539635496355963569635796358963599636096361963629636396364963659636696367963689636996370963719637296373963749637596376963779637896379963809638196382963839638496385963869638796388963899639096391963929639396394963959639696397963989639996400964019640296403964049640596406964079640896409964109641196412964139641496415964169641796418964199642096421964229642396424964259642696427964289642996430964319643296433964349643596436964379643896439964409644196442964439644496445964469644796448964499645096451964529645396454964559645696457964589645996460964619646296463964649646596466964679646896469964709647196472964739647496475964769647796478964799648096481964829648396484964859648696487964889648996490964919649296493964949649596496964979649896499965009650196502965039650496505965069650796508965099651096511965129651396514965159651696517965189651996520965219652296523965249652596526965279652896529965309653196532965339653496535965369653796538965399654096541965429654396544965459654696547965489654996550965519655296553965549655596556965579655896559965609656196562965639656496565965669656796568965699657096571965729657396574965759657696577965789657996580965819658296583965849658596586965879658896589965909659196592965939659496595965969659796598965999660096601966029660396604966059660696607966089660996610966119661296613966149661596616966179661896619966209662196622966239662496625966269662796628966299663096631966329663396634966359663696637966389663996640966419664296643966449664596646966479664896649966509665196652966539665496655966569665796658966599666096661966629666396664966659666696667966689666996670966719667296673966749667596676966779667896679966809668196682966839668496685966869668796688966899669096691966929669396694966959669696697966989669996700967019670296703967049670596706967079670896709967109671196712967139671496715967169671796718967199672096721967229672396724967259672696727967289672996730967319673296733967349673596736967379673896739967409674196742967439674496745967469674796748967499675096751967529675396754967559675696757967589675996760967619676296763967649676596766967679676896769967709677196772967739677496775967769677796778967799678096781967829678396784967859678696787967889678996790967919679296793967949679596796967979679896799968009680196802968039680496805968069680796808968099681096811968129681396814968159681696817968189681996820968219682296823968249682596826968279682896829968309683196832968339683496835968369683796838968399684096841968429684396844968459684696847968489684996850968519685296853968549685596856968579685896859968609686196862968639686496865968669686796868968699687096871968729687396874968759687696877968789687996880968819688296883968849688596886968879688896889968909689196892968939689496895968969689796898968999690096901969029690396904969059690696907969089690996910969119691296913969149691596916969179691896919969209692196922969239692496925969269692796928969299693096931969329693396934969359693696937969389693996940969419694296943969449694596946969479694896949969509695196952969539695496955969569695796958969599696096961969629696396964969659696696967969689696996970969719697296973969749697596976969779697896979969809698196982969839698496985969869698796988969899699096991969929699396994969959699696997969989699997000970019700297003970049700597006970079700897009970109701197012970139701497015970169701797018970199702097021970229702397024970259702697027970289702997030970319703297033970349703597036970379703897039970409704197042970439704497045970469704797048970499705097051970529705397054970559705697057970589705997060970619706297063970649706597066970679706897069970709707197072970739707497075970769707797078970799708097081970829708397084970859708697087970889708997090970919709297093970949709597096970979709897099971009710197102971039710497105971069710797108971099711097111971129711397114971159711697117971189711997120971219712297123971249712597126971279712897129971309713197132971339713497135971369713797138971399714097141971429714397144971459714697147971489714997150971519715297153971549715597156971579715897159971609716197162971639716497165971669716797168971699717097171971729717397174971759717697177971789717997180971819718297183971849718597186971879718897189971909719197192971939719497195971969719797198971999720097201972029720397204972059720697207972089720997210972119721297213972149721597216972179721897219972209722197222972239722497225972269722797228972299723097231972329723397234972359723697237972389723997240972419724297243972449724597246972479724897249972509725197252972539725497255972569725797258972599726097261972629726397264972659726697267972689726997270972719727297273972749727597276972779727897279972809728197282972839728497285972869728797288972899729097291972929729397294972959729697297972989729997300973019730297303973049730597306973079730897309973109731197312973139731497315973169731797318973199732097321973229732397324973259732697327973289732997330973319733297333973349733597336973379733897339973409734197342973439734497345973469734797348973499735097351973529735397354973559735697357973589735997360973619736297363973649736597366973679736897369973709737197372973739737497375973769737797378973799738097381973829738397384973859738697387973889738997390973919739297393973949739597396973979739897399974009740197402974039740497405974069740797408974099741097411974129741397414974159741697417974189741997420974219742297423974249742597426974279742897429974309743197432974339743497435974369743797438974399744097441974429744397444974459744697447974489744997450974519745297453974549745597456974579745897459974609746197462974639746497465974669746797468974699747097471974729747397474974759747697477974789747997480974819748297483974849748597486974879748897489974909749197492974939749497495974969749797498974999750097501975029750397504975059750697507975089750997510975119751297513975149751597516975179751897519975209752197522975239752497525975269752797528975299753097531975329753397534975359753697537975389753997540975419754297543975449754597546975479754897549975509755197552975539755497555975569755797558975599756097561975629756397564975659756697567975689756997570975719757297573975749757597576975779757897579975809758197582975839758497585975869758797588975899759097591975929759397594975959759697597975989759997600976019760297603976049760597606976079760897609976109761197612976139761497615976169761797618976199762097621976229762397624976259762697627976289762997630976319763297633976349763597636976379763897639976409764197642976439764497645976469764797648976499765097651976529765397654976559765697657976589765997660976619766297663976649766597666976679766897669976709767197672976739767497675976769767797678976799768097681976829768397684976859768697687976889768997690976919769297693976949769597696976979769897699977009770197702977039770497705977069770797708977099771097711977129771397714977159771697717977189771997720977219772297723977249772597726977279772897729977309773197732977339773497735977369773797738977399774097741977429774397744977459774697747977489774997750977519775297753977549775597756977579775897759977609776197762977639776497765977669776797768977699777097771977729777397774977759777697777977789777997780977819778297783977849778597786977879778897789977909779197792977939779497795977969779797798977999780097801978029780397804978059780697807978089780997810978119781297813978149781597816978179781897819978209782197822978239782497825978269782797828978299783097831978329783397834978359783697837978389783997840978419784297843978449784597846978479784897849978509785197852978539785497855978569785797858978599786097861978629786397864978659786697867978689786997870978719787297873978749787597876978779787897879978809788197882978839788497885978869788797888978899789097891978929789397894978959789697897978989789997900979019790297903979049790597906979079790897909979109791197912979139791497915979169791797918979199792097921979229792397924979259792697927979289792997930979319793297933979349793597936979379793897939979409794197942979439794497945979469794797948979499795097951979529795397954979559795697957979589795997960979619796297963979649796597966979679796897969979709797197972979739797497975979769797797978979799798097981979829798397984979859798697987979889798997990979919799297993979949799597996979979799897999980009800198002980039800498005980069800798008980099801098011980129801398014980159801698017980189801998020980219802298023980249802598026980279802898029980309803198032980339803498035980369803798038980399804098041980429804398044980459804698047980489804998050980519805298053980549805598056980579805898059980609806198062980639806498065980669806798068980699807098071980729807398074980759807698077980789807998080980819808298083980849808598086980879808898089980909809198092980939809498095980969809798098980999810098101981029810398104981059810698107981089810998110981119811298113981149811598116981179811898119981209812198122981239812498125981269812798128981299813098131981329813398134981359813698137981389813998140981419814298143981449814598146981479814898149981509815198152981539815498155981569815798158981599816098161981629816398164981659816698167981689816998170981719817298173981749817598176981779817898179981809818198182981839818498185981869818798188981899819098191981929819398194981959819698197981989819998200982019820298203982049820598206982079820898209982109821198212982139821498215982169821798218982199822098221982229822398224982259822698227982289822998230982319823298233982349823598236982379823898239982409824198242982439824498245982469824798248982499825098251982529825398254982559825698257982589825998260982619826298263982649826598266982679826898269982709827198272982739827498275982769827798278982799828098281982829828398284982859828698287982889828998290982919829298293982949829598296982979829898299983009830198302983039830498305983069830798308983099831098311983129831398314983159831698317983189831998320983219832298323983249832598326983279832898329983309833198332983339833498335983369833798338983399834098341983429834398344983459834698347983489834998350983519835298353983549835598356983579835898359983609836198362983639836498365983669836798368983699837098371983729837398374983759837698377983789837998380983819838298383983849838598386983879838898389983909839198392983939839498395983969839798398983999840098401984029840398404984059840698407984089840998410984119841298413984149841598416984179841898419984209842198422984239842498425984269842798428984299843098431984329843398434984359843698437984389843998440984419844298443984449844598446984479844898449984509845198452984539845498455
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /**
  186. * Observable that will be called when effect is bound.
  187. */
  188. this.onBindObservable = new BABYLON.Observable();
  189. /** @hidden */
  190. this._bonesComputationForcedToCPU = false;
  191. this._uniformBuffersNames = {};
  192. this._isReady = false;
  193. this._compilationError = "";
  194. this.name = baseName;
  195. if (attributesNamesOrOptions.attributes) {
  196. var options = attributesNamesOrOptions;
  197. this._engine = uniformsNamesOrEngine;
  198. this._attributesNames = options.attributes;
  199. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  200. this._samplers = options.samplers.slice();
  201. this.defines = options.defines;
  202. this.onError = options.onError;
  203. this.onCompiled = options.onCompiled;
  204. this._fallbacks = options.fallbacks;
  205. this._indexParameters = options.indexParameters;
  206. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  207. if (options.uniformBuffersNames) {
  208. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  209. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  210. }
  211. }
  212. }
  213. else {
  214. this._engine = engine;
  215. this.defines = defines;
  216. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  217. this._samplers = samplers ? samplers.slice() : [];
  218. this._attributesNames = attributesNamesOrOptions;
  219. this.onError = onError;
  220. this.onCompiled = onCompiled;
  221. this._indexParameters = indexParameters;
  222. this._fallbacks = fallbacks;
  223. }
  224. this.uniqueId = Effect._uniqueIdSeed++;
  225. var vertexSource;
  226. var fragmentSource;
  227. if (baseName.vertexElement) {
  228. vertexSource = document.getElementById(baseName.vertexElement);
  229. if (!vertexSource) {
  230. vertexSource = baseName.vertexElement;
  231. }
  232. }
  233. else {
  234. vertexSource = baseName.vertex || baseName;
  235. }
  236. if (baseName.fragmentElement) {
  237. fragmentSource = document.getElementById(baseName.fragmentElement);
  238. if (!fragmentSource) {
  239. fragmentSource = baseName.fragmentElement;
  240. }
  241. }
  242. else {
  243. fragmentSource = baseName.fragment || baseName;
  244. }
  245. this._loadVertexShader(vertexSource, function (vertexCode) {
  246. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  247. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  248. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  249. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  250. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  251. if (baseName) {
  252. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  253. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  254. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  255. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  256. }
  257. else {
  258. _this._vertexSourceCode = migratedVertexCode;
  259. _this._fragmentSourceCode = migratedFragmentCode;
  260. }
  261. _this._prepareEffect();
  262. });
  263. });
  264. });
  265. });
  266. });
  267. });
  268. }
  269. Object.defineProperty(Effect.prototype, "key", {
  270. /**
  271. * Unique key for this effect
  272. */
  273. get: function () {
  274. return this._key;
  275. },
  276. enumerable: true,
  277. configurable: true
  278. });
  279. /**
  280. * If the effect has been compiled and prepared.
  281. * @returns if the effect is compiled and prepared.
  282. */
  283. Effect.prototype.isReady = function () {
  284. return this._isReady;
  285. };
  286. /**
  287. * The engine the effect was initialized with.
  288. * @returns the engine.
  289. */
  290. Effect.prototype.getEngine = function () {
  291. return this._engine;
  292. };
  293. /**
  294. * The compiled webGL program for the effect
  295. * @returns the webGL program.
  296. */
  297. Effect.prototype.getProgram = function () {
  298. return this._program;
  299. };
  300. /**
  301. * The set of names of attribute variables for the shader.
  302. * @returns An array of attribute names.
  303. */
  304. Effect.prototype.getAttributesNames = function () {
  305. return this._attributesNames;
  306. };
  307. /**
  308. * Returns the attribute at the given index.
  309. * @param index The index of the attribute.
  310. * @returns The location of the attribute.
  311. */
  312. Effect.prototype.getAttributeLocation = function (index) {
  313. return this._attributes[index];
  314. };
  315. /**
  316. * Returns the attribute based on the name of the variable.
  317. * @param name of the attribute to look up.
  318. * @returns the attribute location.
  319. */
  320. Effect.prototype.getAttributeLocationByName = function (name) {
  321. var index = this._attributesNames.indexOf(name);
  322. return this._attributes[index];
  323. };
  324. /**
  325. * The number of attributes.
  326. * @returns the numnber of attributes.
  327. */
  328. Effect.prototype.getAttributesCount = function () {
  329. return this._attributes.length;
  330. };
  331. /**
  332. * Gets the index of a uniform variable.
  333. * @param uniformName of the uniform to look up.
  334. * @returns the index.
  335. */
  336. Effect.prototype.getUniformIndex = function (uniformName) {
  337. return this._uniformsNames.indexOf(uniformName);
  338. };
  339. /**
  340. * Returns the attribute based on the name of the variable.
  341. * @param uniformName of the uniform to look up.
  342. * @returns the location of the uniform.
  343. */
  344. Effect.prototype.getUniform = function (uniformName) {
  345. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  346. };
  347. /**
  348. * Returns an array of sampler variable names
  349. * @returns The array of sampler variable neames.
  350. */
  351. Effect.prototype.getSamplers = function () {
  352. return this._samplers;
  353. };
  354. /**
  355. * The error from the last compilation.
  356. * @returns the error string.
  357. */
  358. Effect.prototype.getCompilationError = function () {
  359. return this._compilationError;
  360. };
  361. /**
  362. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  363. * @param func The callback to be used.
  364. */
  365. Effect.prototype.executeWhenCompiled = function (func) {
  366. if (this.isReady()) {
  367. func(this);
  368. return;
  369. }
  370. this.onCompileObservable.add(function (effect) {
  371. func(effect);
  372. });
  373. };
  374. /** @hidden */
  375. Effect.prototype._loadVertexShader = function (vertex, callback) {
  376. if (BABYLON.Tools.IsWindowObjectExist()) {
  377. // DOM element ?
  378. if (vertex instanceof HTMLElement) {
  379. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  380. callback(vertexCode);
  381. return;
  382. }
  383. }
  384. // Base64 encoded ?
  385. if (vertex.substr(0, 7) === "base64:") {
  386. var vertexBinary = window.atob(vertex.substr(7));
  387. callback(vertexBinary);
  388. return;
  389. }
  390. // Is in local store ?
  391. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  392. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  393. return;
  394. }
  395. var vertexShaderUrl;
  396. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  397. vertexShaderUrl = vertex;
  398. }
  399. else {
  400. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  401. }
  402. // Vertex shader
  403. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  404. };
  405. /** @hidden */
  406. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  407. if (BABYLON.Tools.IsWindowObjectExist()) {
  408. // DOM element ?
  409. if (fragment instanceof HTMLElement) {
  410. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  411. callback(fragmentCode);
  412. return;
  413. }
  414. }
  415. // Base64 encoded ?
  416. if (fragment.substr(0, 7) === "base64:") {
  417. var fragmentBinary = window.atob(fragment.substr(7));
  418. callback(fragmentBinary);
  419. return;
  420. }
  421. // Is in local store ?
  422. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  423. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  424. return;
  425. }
  426. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  427. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  428. return;
  429. }
  430. var fragmentShaderUrl;
  431. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  432. fragmentShaderUrl = fragment;
  433. }
  434. else {
  435. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  436. }
  437. // Fragment shader
  438. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  439. };
  440. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  441. // Rebuild shaders source code
  442. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  443. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  444. vertexCode = prefix + vertexCode;
  445. fragmentCode = prefix + fragmentCode;
  446. // Number lines of shaders source code
  447. var i = 2;
  448. var regex = /\n/gm;
  449. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  450. i = 2;
  451. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  452. // Dump shaders name and formatted source code
  453. if (this.name.vertexElement) {
  454. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  455. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  456. }
  457. else if (this.name.vertex) {
  458. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  459. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  460. }
  461. else {
  462. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  463. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  464. }
  465. };
  466. ;
  467. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  468. var preparedSourceCode = this._processPrecision(sourceCode);
  469. if (this._engine.webGLVersion == 1) {
  470. callback(preparedSourceCode);
  471. return;
  472. }
  473. // Already converted
  474. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  475. callback(preparedSourceCode.replace("#version 300 es", ""));
  476. return;
  477. }
  478. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  479. // Remove extensions
  480. // #extension GL_OES_standard_derivatives : enable
  481. // #extension GL_EXT_shader_texture_lod : enable
  482. // #extension GL_EXT_frag_depth : enable
  483. // #extension GL_EXT_draw_buffers : require
  484. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  485. var result = preparedSourceCode.replace(regex, "");
  486. // Migrate to GLSL v300
  487. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  488. result = result.replace(/attribute[ \t]/g, "in ");
  489. result = result.replace(/[ \t]attribute/g, " in");
  490. if (isFragment) {
  491. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  492. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  493. result = result.replace(/texture2D\s*\(/g, "texture(");
  494. result = result.replace(/textureCube\s*\(/g, "texture(");
  495. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  496. result = result.replace(/gl_FragColor/g, "glFragColor");
  497. result = result.replace(/gl_FragData/g, "glFragData");
  498. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  499. }
  500. callback(result);
  501. };
  502. Effect.prototype._processIncludes = function (sourceCode, callback) {
  503. var _this = this;
  504. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  505. var match = regex.exec(sourceCode);
  506. var returnValue = new String(sourceCode);
  507. while (match != null) {
  508. var includeFile = match[1];
  509. // Uniform declaration
  510. if (includeFile.indexOf("__decl__") !== -1) {
  511. includeFile = includeFile.replace(/__decl__/, "");
  512. if (this._engine.supportsUniformBuffers) {
  513. includeFile = includeFile.replace(/Vertex/, "Ubo");
  514. includeFile = includeFile.replace(/Fragment/, "Ubo");
  515. }
  516. includeFile = includeFile + "Declaration";
  517. }
  518. if (Effect.IncludesShadersStore[includeFile]) {
  519. // Substitution
  520. var includeContent = Effect.IncludesShadersStore[includeFile];
  521. if (match[2]) {
  522. var splits = match[3].split(",");
  523. for (var index = 0; index < splits.length; index += 2) {
  524. var source = new RegExp(splits[index], "g");
  525. var dest = splits[index + 1];
  526. includeContent = includeContent.replace(source, dest);
  527. }
  528. }
  529. if (match[4]) {
  530. var indexString = match[5];
  531. if (indexString.indexOf("..") !== -1) {
  532. var indexSplits = indexString.split("..");
  533. var minIndex = parseInt(indexSplits[0]);
  534. var maxIndex = parseInt(indexSplits[1]);
  535. var sourceIncludeContent = includeContent.slice(0);
  536. includeContent = "";
  537. if (isNaN(maxIndex)) {
  538. maxIndex = this._indexParameters[indexSplits[1]];
  539. }
  540. for (var i = minIndex; i < maxIndex; i++) {
  541. if (!this._engine.supportsUniformBuffers) {
  542. // Ubo replacement
  543. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  544. return p1 + "{X}";
  545. });
  546. }
  547. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  548. }
  549. }
  550. else {
  551. if (!this._engine.supportsUniformBuffers) {
  552. // Ubo replacement
  553. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  554. return p1 + "{X}";
  555. });
  556. }
  557. includeContent = includeContent.replace(/\{X\}/g, indexString);
  558. }
  559. }
  560. // Replace
  561. returnValue = returnValue.replace(match[0], includeContent);
  562. }
  563. else {
  564. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  565. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  566. Effect.IncludesShadersStore[includeFile] = fileContent;
  567. _this._processIncludes(returnValue, callback);
  568. });
  569. return;
  570. }
  571. match = regex.exec(sourceCode);
  572. }
  573. callback(returnValue);
  574. };
  575. Effect.prototype._processPrecision = function (source) {
  576. if (source.indexOf("precision highp float") === -1) {
  577. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  578. source = "precision mediump float;\n" + source;
  579. }
  580. else {
  581. source = "precision highp float;\n" + source;
  582. }
  583. }
  584. else {
  585. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  586. source = source.replace("precision highp float", "precision mediump float");
  587. }
  588. }
  589. return source;
  590. };
  591. /**
  592. * Recompiles the webGL program
  593. * @param vertexSourceCode The source code for the vertex shader.
  594. * @param fragmentSourceCode The source code for the fragment shader.
  595. * @param onCompiled Callback called when completed.
  596. * @param onError Callback called on error.
  597. */
  598. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  599. var _this = this;
  600. this._isReady = false;
  601. this._vertexSourceCodeOverride = vertexSourceCode;
  602. this._fragmentSourceCodeOverride = fragmentSourceCode;
  603. this.onError = function (effect, error) {
  604. if (onError) {
  605. onError(error);
  606. }
  607. };
  608. this.onCompiled = function () {
  609. var scenes = _this.getEngine().scenes;
  610. for (var i = 0; i < scenes.length; i++) {
  611. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  612. }
  613. if (onCompiled) {
  614. onCompiled(_this._program);
  615. }
  616. };
  617. this._fallbacks = null;
  618. this._prepareEffect();
  619. };
  620. /**
  621. * Gets the uniform locations of the the specified variable names
  622. * @param names THe names of the variables to lookup.
  623. * @returns Array of locations in the same order as variable names.
  624. */
  625. Effect.prototype.getSpecificUniformLocations = function (names) {
  626. var engine = this._engine;
  627. return engine.getUniforms(this._program, names);
  628. };
  629. /**
  630. * Prepares the effect
  631. */
  632. Effect.prototype._prepareEffect = function () {
  633. var attributesNames = this._attributesNames;
  634. var defines = this.defines;
  635. var fallbacks = this._fallbacks;
  636. this._valueCache = {};
  637. var previousProgram = this._program;
  638. try {
  639. var engine = this._engine;
  640. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  641. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  642. }
  643. else {
  644. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  645. }
  646. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  647. if (engine.supportsUniformBuffers) {
  648. for (var name in this._uniformBuffersNames) {
  649. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  650. }
  651. }
  652. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  653. this._attributes = engine.getAttributes(this._program, attributesNames);
  654. var index;
  655. for (index = 0; index < this._samplers.length; index++) {
  656. var sampler = this.getUniform(this._samplers[index]);
  657. if (sampler == null) {
  658. this._samplers.splice(index, 1);
  659. index--;
  660. }
  661. }
  662. engine.bindSamplers(this);
  663. this._compilationError = "";
  664. this._isReady = true;
  665. if (this.onCompiled) {
  666. this.onCompiled(this);
  667. }
  668. this.onCompileObservable.notifyObservers(this);
  669. this.onCompileObservable.clear();
  670. // Unbind mesh reference in fallbacks
  671. if (this._fallbacks) {
  672. this._fallbacks.unBindMesh();
  673. }
  674. if (previousProgram) {
  675. this.getEngine()._deleteProgram(previousProgram);
  676. }
  677. }
  678. catch (e) {
  679. this._compilationError = e.message;
  680. // Let's go through fallbacks then
  681. BABYLON.Tools.Error("Unable to compile effect:");
  682. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  683. return " " + uniform;
  684. }));
  685. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  686. return " " + attribute;
  687. }));
  688. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  689. BABYLON.Tools.Error("Error: " + this._compilationError);
  690. if (previousProgram) {
  691. this._program = previousProgram;
  692. this._isReady = true;
  693. if (this.onError) {
  694. this.onError(this, this._compilationError);
  695. }
  696. this.onErrorObservable.notifyObservers(this);
  697. }
  698. if (fallbacks && fallbacks.isMoreFallbacks) {
  699. BABYLON.Tools.Error("Trying next fallback.");
  700. this.defines = fallbacks.reduce(this.defines, this);
  701. this._prepareEffect();
  702. }
  703. else { // Sorry we did everything we can
  704. if (this.onError) {
  705. this.onError(this, this._compilationError);
  706. }
  707. this.onErrorObservable.notifyObservers(this);
  708. this.onErrorObservable.clear();
  709. // Unbind mesh reference in fallbacks
  710. if (this._fallbacks) {
  711. this._fallbacks.unBindMesh();
  712. }
  713. }
  714. }
  715. };
  716. Object.defineProperty(Effect.prototype, "isSupported", {
  717. /**
  718. * Checks if the effect is supported. (Must be called after compilation)
  719. */
  720. get: function () {
  721. return this._compilationError === "";
  722. },
  723. enumerable: true,
  724. configurable: true
  725. });
  726. /**
  727. * Binds a texture to the engine to be used as output of the shader.
  728. * @param channel Name of the output variable.
  729. * @param texture Texture to bind.
  730. */
  731. Effect.prototype._bindTexture = function (channel, texture) {
  732. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  733. };
  734. /**
  735. * Sets a texture on the engine to be used in the shader.
  736. * @param channel Name of the sampler variable.
  737. * @param texture Texture to set.
  738. */
  739. Effect.prototype.setTexture = function (channel, texture) {
  740. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  741. };
  742. /**
  743. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  744. * @param channel Name of the sampler variable.
  745. * @param texture Texture to set.
  746. */
  747. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  748. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  749. };
  750. /**
  751. * Sets an array of textures on the engine to be used in the shader.
  752. * @param channel Name of the variable.
  753. * @param textures Textures to set.
  754. */
  755. Effect.prototype.setTextureArray = function (channel, textures) {
  756. if (this._samplers.indexOf(channel + "Ex") === -1) {
  757. var initialPos = this._samplers.indexOf(channel);
  758. for (var index = 1; index < textures.length; index++) {
  759. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  760. }
  761. }
  762. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  763. };
  764. /**
  765. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  766. * @param channel Name of the sampler variable.
  767. * @param postProcess Post process to get the input texture from.
  768. */
  769. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  770. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  771. };
  772. /**
  773. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  774. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  775. * @param channel Name of the sampler variable.
  776. * @param postProcess Post process to get the output texture from.
  777. */
  778. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  779. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  780. };
  781. /** @hidden */
  782. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  783. var cache = this._valueCache[uniformName];
  784. var flag = matrix.updateFlag;
  785. if (cache !== undefined && cache === flag) {
  786. return false;
  787. }
  788. this._valueCache[uniformName] = flag;
  789. return true;
  790. };
  791. /** @hidden */
  792. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  793. var cache = this._valueCache[uniformName];
  794. if (!cache) {
  795. cache = [x, y];
  796. this._valueCache[uniformName] = cache;
  797. return true;
  798. }
  799. var changed = false;
  800. if (cache[0] !== x) {
  801. cache[0] = x;
  802. changed = true;
  803. }
  804. if (cache[1] !== y) {
  805. cache[1] = y;
  806. changed = true;
  807. }
  808. return changed;
  809. };
  810. /** @hidden */
  811. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  812. var cache = this._valueCache[uniformName];
  813. if (!cache) {
  814. cache = [x, y, z];
  815. this._valueCache[uniformName] = cache;
  816. return true;
  817. }
  818. var changed = false;
  819. if (cache[0] !== x) {
  820. cache[0] = x;
  821. changed = true;
  822. }
  823. if (cache[1] !== y) {
  824. cache[1] = y;
  825. changed = true;
  826. }
  827. if (cache[2] !== z) {
  828. cache[2] = z;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /** @hidden */
  834. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  835. var cache = this._valueCache[uniformName];
  836. if (!cache) {
  837. cache = [x, y, z, w];
  838. this._valueCache[uniformName] = cache;
  839. return true;
  840. }
  841. var changed = false;
  842. if (cache[0] !== x) {
  843. cache[0] = x;
  844. changed = true;
  845. }
  846. if (cache[1] !== y) {
  847. cache[1] = y;
  848. changed = true;
  849. }
  850. if (cache[2] !== z) {
  851. cache[2] = z;
  852. changed = true;
  853. }
  854. if (cache[3] !== w) {
  855. cache[3] = w;
  856. changed = true;
  857. }
  858. return changed;
  859. };
  860. /**
  861. * Binds a buffer to a uniform.
  862. * @param buffer Buffer to bind.
  863. * @param name Name of the uniform variable to bind to.
  864. */
  865. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  866. var bufferName = this._uniformBuffersNames[name];
  867. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  868. return;
  869. }
  870. Effect._baseCache[bufferName] = buffer;
  871. this._engine.bindUniformBufferBase(buffer, bufferName);
  872. };
  873. /**
  874. * Binds block to a uniform.
  875. * @param blockName Name of the block to bind.
  876. * @param index Index to bind.
  877. */
  878. Effect.prototype.bindUniformBlock = function (blockName, index) {
  879. this._engine.bindUniformBlock(this._program, blockName, index);
  880. };
  881. /**
  882. * Sets an interger value on a uniform variable.
  883. * @param uniformName Name of the variable.
  884. * @param value Value to be set.
  885. * @returns this effect.
  886. */
  887. Effect.prototype.setInt = function (uniformName, value) {
  888. var cache = this._valueCache[uniformName];
  889. if (cache !== undefined && cache === value)
  890. return this;
  891. this._valueCache[uniformName] = value;
  892. this._engine.setInt(this.getUniform(uniformName), value);
  893. return this;
  894. };
  895. /**
  896. * Sets an int array on a uniform variable.
  897. * @param uniformName Name of the variable.
  898. * @param array array to be set.
  899. * @returns this effect.
  900. */
  901. Effect.prototype.setIntArray = function (uniformName, array) {
  902. this._valueCache[uniformName] = null;
  903. this._engine.setIntArray(this.getUniform(uniformName), array);
  904. return this;
  905. };
  906. /**
  907. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  908. * @param uniformName Name of the variable.
  909. * @param array array to be set.
  910. * @returns this effect.
  911. */
  912. Effect.prototype.setIntArray2 = function (uniformName, array) {
  913. this._valueCache[uniformName] = null;
  914. this._engine.setIntArray2(this.getUniform(uniformName), array);
  915. return this;
  916. };
  917. /**
  918. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  919. * @param uniformName Name of the variable.
  920. * @param array array to be set.
  921. * @returns this effect.
  922. */
  923. Effect.prototype.setIntArray3 = function (uniformName, array) {
  924. this._valueCache[uniformName] = null;
  925. this._engine.setIntArray3(this.getUniform(uniformName), array);
  926. return this;
  927. };
  928. /**
  929. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  930. * @param uniformName Name of the variable.
  931. * @param array array to be set.
  932. * @returns this effect.
  933. */
  934. Effect.prototype.setIntArray4 = function (uniformName, array) {
  935. this._valueCache[uniformName] = null;
  936. this._engine.setIntArray4(this.getUniform(uniformName), array);
  937. return this;
  938. };
  939. /**
  940. * Sets an float array on a uniform variable.
  941. * @param uniformName Name of the variable.
  942. * @param array array to be set.
  943. * @returns this effect.
  944. */
  945. Effect.prototype.setFloatArray = function (uniformName, array) {
  946. this._valueCache[uniformName] = null;
  947. this._engine.setFloatArray(this.getUniform(uniformName), array);
  948. return this;
  949. };
  950. /**
  951. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  952. * @param uniformName Name of the variable.
  953. * @param array array to be set.
  954. * @returns this effect.
  955. */
  956. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  957. this._valueCache[uniformName] = null;
  958. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  959. return this;
  960. };
  961. /**
  962. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  963. * @param uniformName Name of the variable.
  964. * @param array array to be set.
  965. * @returns this effect.
  966. */
  967. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  968. this._valueCache[uniformName] = null;
  969. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  970. return this;
  971. };
  972. /**
  973. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  974. * @param uniformName Name of the variable.
  975. * @param array array to be set.
  976. * @returns this effect.
  977. */
  978. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  979. this._valueCache[uniformName] = null;
  980. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  981. return this;
  982. };
  983. /**
  984. * Sets an array on a uniform variable.
  985. * @param uniformName Name of the variable.
  986. * @param array array to be set.
  987. * @returns this effect.
  988. */
  989. Effect.prototype.setArray = function (uniformName, array) {
  990. this._valueCache[uniformName] = null;
  991. this._engine.setArray(this.getUniform(uniformName), array);
  992. return this;
  993. };
  994. /**
  995. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  996. * @param uniformName Name of the variable.
  997. * @param array array to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setArray2 = function (uniformName, array) {
  1001. this._valueCache[uniformName] = null;
  1002. this._engine.setArray2(this.getUniform(uniformName), array);
  1003. return this;
  1004. };
  1005. /**
  1006. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1007. * @param uniformName Name of the variable.
  1008. * @param array array to be set.
  1009. * @returns this effect.
  1010. */
  1011. Effect.prototype.setArray3 = function (uniformName, array) {
  1012. this._valueCache[uniformName] = null;
  1013. this._engine.setArray3(this.getUniform(uniformName), array);
  1014. return this;
  1015. };
  1016. /**
  1017. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1018. * @param uniformName Name of the variable.
  1019. * @param array array to be set.
  1020. * @returns this effect.
  1021. */
  1022. Effect.prototype.setArray4 = function (uniformName, array) {
  1023. this._valueCache[uniformName] = null;
  1024. this._engine.setArray4(this.getUniform(uniformName), array);
  1025. return this;
  1026. };
  1027. /**
  1028. * Sets matrices on a uniform variable.
  1029. * @param uniformName Name of the variable.
  1030. * @param matrices matrices to be set.
  1031. * @returns this effect.
  1032. */
  1033. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1034. if (!matrices) {
  1035. return this;
  1036. }
  1037. this._valueCache[uniformName] = null;
  1038. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1039. return this;
  1040. };
  1041. /**
  1042. * Sets matrix on a uniform variable.
  1043. * @param uniformName Name of the variable.
  1044. * @param matrix matrix to be set.
  1045. * @returns this effect.
  1046. */
  1047. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1048. if (this._cacheMatrix(uniformName, matrix)) {
  1049. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1050. }
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1060. this._valueCache[uniformName] = null;
  1061. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1062. return this;
  1063. };
  1064. /**
  1065. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1066. * @param uniformName Name of the variable.
  1067. * @param matrix matrix to be set.
  1068. * @returns this effect.
  1069. */
  1070. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1071. this._valueCache[uniformName] = null;
  1072. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1073. return this;
  1074. };
  1075. /**
  1076. * Sets a float on a uniform variable.
  1077. * @param uniformName Name of the variable.
  1078. * @param value value to be set.
  1079. * @returns this effect.
  1080. */
  1081. Effect.prototype.setFloat = function (uniformName, value) {
  1082. var cache = this._valueCache[uniformName];
  1083. if (cache !== undefined && cache === value)
  1084. return this;
  1085. this._valueCache[uniformName] = value;
  1086. this._engine.setFloat(this.getUniform(uniformName), value);
  1087. return this;
  1088. };
  1089. /**
  1090. * Sets a boolean on a uniform variable.
  1091. * @param uniformName Name of the variable.
  1092. * @param bool value to be set.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setBool = function (uniformName, bool) {
  1096. var cache = this._valueCache[uniformName];
  1097. if (cache !== undefined && cache === bool)
  1098. return this;
  1099. this._valueCache[uniformName] = bool;
  1100. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1101. return this;
  1102. };
  1103. /**
  1104. * Sets a Vector2 on a uniform variable.
  1105. * @param uniformName Name of the variable.
  1106. * @param vector2 vector2 to be set.
  1107. * @returns this effect.
  1108. */
  1109. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1110. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1111. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1112. }
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a float2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param x First float in float2.
  1119. * @param y Second float in float2.
  1120. * @returns this effect.
  1121. */
  1122. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1123. if (this._cacheFloat2(uniformName, x, y)) {
  1124. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1125. }
  1126. return this;
  1127. };
  1128. /**
  1129. * Sets a Vector3 on a uniform variable.
  1130. * @param uniformName Name of the variable.
  1131. * @param vector3 Value to be set.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1135. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1136. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a float3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param x First float in float3.
  1144. * @param y Second float in float3.
  1145. * @param z Third float in float3.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1149. if (this._cacheFloat3(uniformName, x, y, z)) {
  1150. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Vector4 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param vector4 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1161. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a float4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param x First float in float4.
  1170. * @param y Second float in float4.
  1171. * @param z Third float in float4.
  1172. * @param w Fourth float in float4.
  1173. * @returns this effect.
  1174. */
  1175. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1176. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1177. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1178. }
  1179. return this;
  1180. };
  1181. /**
  1182. * Sets a Color3 on a uniform variable.
  1183. * @param uniformName Name of the variable.
  1184. * @param color3 Value to be set.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setColor3 = function (uniformName, color3) {
  1188. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1189. this._engine.setColor3(this.getUniform(uniformName), color3);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color4 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @param alpha Alpha value to be set.
  1198. * @returns this effect.
  1199. */
  1200. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1201. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1202. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1203. }
  1204. return this;
  1205. };
  1206. /**
  1207. * Sets a Color4 on a uniform variable
  1208. * @param uniformName defines the name of the variable
  1209. * @param color4 defines the value to be set
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1213. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1214. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Resets the cache of effects.
  1220. */
  1221. Effect.ResetCache = function () {
  1222. Effect._baseCache = {};
  1223. };
  1224. Effect._uniqueIdSeed = 0;
  1225. Effect._baseCache = {};
  1226. /**
  1227. * Store of each shader (The can be looked up using effect.key)
  1228. */
  1229. Effect.ShadersStore = {};
  1230. /**
  1231. * Store of each included file for a shader (The can be looked up using effect.key)
  1232. */
  1233. Effect.IncludesShadersStore = {};
  1234. return Effect;
  1235. }());
  1236. BABYLON.Effect = Effect;
  1237. })(BABYLON || (BABYLON = {}));
  1238. //# sourceMappingURL=babylon.effect.js.map
  1239. //# sourceMappingURL=babylon.types.js.map
  1240. var BABYLON;
  1241. (function (BABYLON) {
  1242. var KeyboardEventTypes = /** @class */ (function () {
  1243. function KeyboardEventTypes() {
  1244. }
  1245. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1246. get: function () {
  1247. return KeyboardEventTypes._KEYDOWN;
  1248. },
  1249. enumerable: true,
  1250. configurable: true
  1251. });
  1252. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1253. get: function () {
  1254. return KeyboardEventTypes._KEYUP;
  1255. },
  1256. enumerable: true,
  1257. configurable: true
  1258. });
  1259. KeyboardEventTypes._KEYDOWN = 0x01;
  1260. KeyboardEventTypes._KEYUP = 0x02;
  1261. return KeyboardEventTypes;
  1262. }());
  1263. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1264. var KeyboardInfo = /** @class */ (function () {
  1265. function KeyboardInfo(type, event) {
  1266. this.type = type;
  1267. this.event = event;
  1268. }
  1269. return KeyboardInfo;
  1270. }());
  1271. BABYLON.KeyboardInfo = KeyboardInfo;
  1272. /**
  1273. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1274. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1275. */
  1276. var KeyboardInfoPre = /** @class */ (function (_super) {
  1277. __extends(KeyboardInfoPre, _super);
  1278. function KeyboardInfoPre(type, event) {
  1279. var _this = _super.call(this, type, event) || this;
  1280. _this.skipOnPointerObservable = false;
  1281. return _this;
  1282. }
  1283. return KeyboardInfoPre;
  1284. }(KeyboardInfo));
  1285. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1286. })(BABYLON || (BABYLON = {}));
  1287. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1288. var BABYLON;
  1289. (function (BABYLON) {
  1290. var PointerEventTypes = /** @class */ (function () {
  1291. function PointerEventTypes() {
  1292. }
  1293. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1294. get: function () {
  1295. return PointerEventTypes._POINTERDOWN;
  1296. },
  1297. enumerable: true,
  1298. configurable: true
  1299. });
  1300. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1301. get: function () {
  1302. return PointerEventTypes._POINTERUP;
  1303. },
  1304. enumerable: true,
  1305. configurable: true
  1306. });
  1307. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1308. get: function () {
  1309. return PointerEventTypes._POINTERMOVE;
  1310. },
  1311. enumerable: true,
  1312. configurable: true
  1313. });
  1314. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1315. get: function () {
  1316. return PointerEventTypes._POINTERWHEEL;
  1317. },
  1318. enumerable: true,
  1319. configurable: true
  1320. });
  1321. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1322. get: function () {
  1323. return PointerEventTypes._POINTERPICK;
  1324. },
  1325. enumerable: true,
  1326. configurable: true
  1327. });
  1328. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1329. get: function () {
  1330. return PointerEventTypes._POINTERTAP;
  1331. },
  1332. enumerable: true,
  1333. configurable: true
  1334. });
  1335. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1336. get: function () {
  1337. return PointerEventTypes._POINTERDOUBLETAP;
  1338. },
  1339. enumerable: true,
  1340. configurable: true
  1341. });
  1342. PointerEventTypes._POINTERDOWN = 0x01;
  1343. PointerEventTypes._POINTERUP = 0x02;
  1344. PointerEventTypes._POINTERMOVE = 0x04;
  1345. PointerEventTypes._POINTERWHEEL = 0x08;
  1346. PointerEventTypes._POINTERPICK = 0x10;
  1347. PointerEventTypes._POINTERTAP = 0x20;
  1348. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1349. return PointerEventTypes;
  1350. }());
  1351. BABYLON.PointerEventTypes = PointerEventTypes;
  1352. var PointerInfoBase = /** @class */ (function () {
  1353. function PointerInfoBase(type, event) {
  1354. this.type = type;
  1355. this.event = event;
  1356. }
  1357. return PointerInfoBase;
  1358. }());
  1359. BABYLON.PointerInfoBase = PointerInfoBase;
  1360. /**
  1361. * This class is used to store pointer related info for the onPrePointerObservable event.
  1362. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1363. */
  1364. var PointerInfoPre = /** @class */ (function (_super) {
  1365. __extends(PointerInfoPre, _super);
  1366. function PointerInfoPre(type, event, localX, localY) {
  1367. var _this = _super.call(this, type, event) || this;
  1368. _this.skipOnPointerObservable = false;
  1369. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1370. return _this;
  1371. }
  1372. return PointerInfoPre;
  1373. }(PointerInfoBase));
  1374. BABYLON.PointerInfoPre = PointerInfoPre;
  1375. /**
  1376. * This type contains all the data related to a pointer event in Babylon.js.
  1377. * 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.
  1378. */
  1379. var PointerInfo = /** @class */ (function (_super) {
  1380. __extends(PointerInfo, _super);
  1381. function PointerInfo(type, event, pickInfo) {
  1382. var _this = _super.call(this, type, event) || this;
  1383. _this.pickInfo = pickInfo;
  1384. return _this;
  1385. }
  1386. return PointerInfo;
  1387. }(PointerInfoBase));
  1388. BABYLON.PointerInfo = PointerInfo;
  1389. })(BABYLON || (BABYLON = {}));
  1390. //# sourceMappingURL=babylon.pointerEvents.js.map
  1391. var BABYLON;
  1392. (function (BABYLON) {
  1393. BABYLON.ToGammaSpace = 1 / 2.2;
  1394. BABYLON.ToLinearSpace = 2.2;
  1395. BABYLON.Epsilon = 0.001;
  1396. /**
  1397. * Class used to hold a RBG color
  1398. */
  1399. var Color3 = /** @class */ (function () {
  1400. /**
  1401. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1402. * @param r defines the red component (between 0 and 1, default is 0)
  1403. * @param g defines the green component (between 0 and 1, default is 0)
  1404. * @param b defines the blue component (between 0 and 1, default is 0)
  1405. */
  1406. function Color3(
  1407. /**
  1408. * Defines the red component (between 0 and 1, default is 0)
  1409. */
  1410. r,
  1411. /**
  1412. * Defines the green component (between 0 and 1, default is 0)
  1413. */
  1414. g,
  1415. /**
  1416. * Defines the blue component (between 0 and 1, default is 0)
  1417. */
  1418. b) {
  1419. if (r === void 0) { r = 0; }
  1420. if (g === void 0) { g = 0; }
  1421. if (b === void 0) { b = 0; }
  1422. this.r = r;
  1423. this.g = g;
  1424. this.b = b;
  1425. }
  1426. /**
  1427. * Creates a string with the Color3 current values
  1428. * @returns the string representation of the Color3 object
  1429. */
  1430. Color3.prototype.toString = function () {
  1431. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1432. };
  1433. /**
  1434. * Returns the string "Color3"
  1435. * @returns "Color3"
  1436. */
  1437. Color3.prototype.getClassName = function () {
  1438. return "Color3";
  1439. };
  1440. /**
  1441. * Compute the Color3 hash code
  1442. * @returns an unique number that can be used to hash Color3 objects
  1443. */
  1444. Color3.prototype.getHashCode = function () {
  1445. var hash = this.r || 0;
  1446. hash = (hash * 397) ^ (this.g || 0);
  1447. hash = (hash * 397) ^ (this.b || 0);
  1448. return hash;
  1449. };
  1450. // Operators
  1451. /**
  1452. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1453. * @param array defines the array where to store the r,g,b components
  1454. * @param index defines an optional index in the target array to define where to start storing values
  1455. * @returns the current Color3 object
  1456. */
  1457. Color3.prototype.toArray = function (array, index) {
  1458. if (index === undefined) {
  1459. index = 0;
  1460. }
  1461. array[index] = this.r;
  1462. array[index + 1] = this.g;
  1463. array[index + 2] = this.b;
  1464. return this;
  1465. };
  1466. /**
  1467. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1468. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1469. * @returns a new {BABYLON.Color4} object
  1470. */
  1471. Color3.prototype.toColor4 = function (alpha) {
  1472. if (alpha === void 0) { alpha = 1; }
  1473. return new Color4(this.r, this.g, this.b, alpha);
  1474. };
  1475. /**
  1476. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1477. * @returns the new array
  1478. */
  1479. Color3.prototype.asArray = function () {
  1480. var result = new Array();
  1481. this.toArray(result, 0);
  1482. return result;
  1483. };
  1484. /**
  1485. * Returns the luminance value
  1486. * @returns a float value
  1487. */
  1488. Color3.prototype.toLuminance = function () {
  1489. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1490. };
  1491. /**
  1492. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1493. * @param otherColor defines the second operand
  1494. * @returns the new Color3 object
  1495. */
  1496. Color3.prototype.multiply = function (otherColor) {
  1497. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1498. };
  1499. /**
  1500. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1501. * @param otherColor defines the second operand
  1502. * @param result defines the Color3 object where to store the result
  1503. * @returns the current Color3
  1504. */
  1505. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1506. result.r = this.r * otherColor.r;
  1507. result.g = this.g * otherColor.g;
  1508. result.b = this.b * otherColor.b;
  1509. return this;
  1510. };
  1511. /**
  1512. * Determines equality between Color3 objects
  1513. * @param otherColor defines the second operand
  1514. * @returns true if the rgb values are equal to the given ones
  1515. */
  1516. Color3.prototype.equals = function (otherColor) {
  1517. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1518. };
  1519. /**
  1520. * Determines equality between the current Color3 object and a set of r,b,g values
  1521. * @param r defines the red component to check
  1522. * @param g defines the green component to check
  1523. * @param b defines the blue component to check
  1524. * @returns true if the rgb values are equal to the given ones
  1525. */
  1526. Color3.prototype.equalsFloats = function (r, g, b) {
  1527. return this.r === r && this.g === g && this.b === b;
  1528. };
  1529. /**
  1530. * Multiplies in place each rgb value by scale
  1531. * @param scale defines the scaling factor
  1532. * @returns the updated Color3
  1533. */
  1534. Color3.prototype.scale = function (scale) {
  1535. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1536. };
  1537. /**
  1538. * Multiplies the rgb values by scale and stores the result into "result"
  1539. * @param scale defines the scaling factor
  1540. * @param result defines the Color3 object where to store the result
  1541. * @returns the unmodified current Color3
  1542. */
  1543. Color3.prototype.scaleToRef = function (scale, result) {
  1544. result.r = this.r * scale;
  1545. result.g = this.g * scale;
  1546. result.b = this.b * scale;
  1547. return this;
  1548. };
  1549. /**
  1550. * Scale the current Color3 values by a factor and add the result to a given Color3
  1551. * @param scale defines the scale factor
  1552. * @param result defines color to store the result into
  1553. * @returns the unmodified current Color3
  1554. */
  1555. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1556. result.r += this.r * scale;
  1557. result.g += this.g * scale;
  1558. result.b += this.b * scale;
  1559. return this;
  1560. };
  1561. /**
  1562. * Clamps the rgb values by the min and max values and stores the result into "result"
  1563. * @param min defines minimum clamping value (default is 0)
  1564. * @param max defines maximum clamping value (default is 1)
  1565. * @param result defines color to store the result into
  1566. * @returns the original Color3
  1567. */
  1568. Color3.prototype.clampToRef = function (min, max, result) {
  1569. if (min === void 0) { min = 0; }
  1570. if (max === void 0) { max = 1; }
  1571. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1572. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1573. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1574. return this;
  1575. };
  1576. /**
  1577. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1578. * @param otherColor defines the second operand
  1579. * @returns the new Color3
  1580. */
  1581. Color3.prototype.add = function (otherColor) {
  1582. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1583. };
  1584. /**
  1585. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1586. * @param otherColor defines the second operand
  1587. * @param result defines Color3 object to store the result into
  1588. * @returns the unmodified current Color3
  1589. */
  1590. Color3.prototype.addToRef = function (otherColor, result) {
  1591. result.r = this.r + otherColor.r;
  1592. result.g = this.g + otherColor.g;
  1593. result.b = this.b + otherColor.b;
  1594. return this;
  1595. };
  1596. /**
  1597. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1598. * @param otherColor defines the second operand
  1599. * @returns the new Color3
  1600. */
  1601. Color3.prototype.subtract = function (otherColor) {
  1602. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1603. };
  1604. /**
  1605. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1606. * @param otherColor defines the second operand
  1607. * @param result defines Color3 object to store the result into
  1608. * @returns the unmodified current Color3
  1609. */
  1610. Color3.prototype.subtractToRef = function (otherColor, result) {
  1611. result.r = this.r - otherColor.r;
  1612. result.g = this.g - otherColor.g;
  1613. result.b = this.b - otherColor.b;
  1614. return this;
  1615. };
  1616. /**
  1617. * Copy the current object
  1618. * @returns a new Color3 copied the current one
  1619. */
  1620. Color3.prototype.clone = function () {
  1621. return new Color3(this.r, this.g, this.b);
  1622. };
  1623. /**
  1624. * Copies the rgb values from the source in the current Color3
  1625. * @param source defines the source Color3 object
  1626. * @returns the updated Color3 object
  1627. */
  1628. Color3.prototype.copyFrom = function (source) {
  1629. this.r = source.r;
  1630. this.g = source.g;
  1631. this.b = source.b;
  1632. return this;
  1633. };
  1634. /**
  1635. * Updates the Color3 rgb values from the given floats
  1636. * @param r defines the red component to read from
  1637. * @param g defines the green component to read from
  1638. * @param b defines the blue component to read from
  1639. * @returns the current Color3 object
  1640. */
  1641. Color3.prototype.copyFromFloats = function (r, g, b) {
  1642. this.r = r;
  1643. this.g = g;
  1644. this.b = b;
  1645. return this;
  1646. };
  1647. /**
  1648. * Updates the Color3 rgb values from the given floats
  1649. * @param r defines the red component to read from
  1650. * @param g defines the green component to read from
  1651. * @param b defines the blue component to read from
  1652. * @returns the current Color3 object
  1653. */
  1654. Color3.prototype.set = function (r, g, b) {
  1655. return this.copyFromFloats(r, g, b);
  1656. };
  1657. /**
  1658. * Compute the Color3 hexadecimal code as a string
  1659. * @returns a string containing the hexadecimal representation of the Color3 object
  1660. */
  1661. Color3.prototype.toHexString = function () {
  1662. var intR = (this.r * 255) | 0;
  1663. var intG = (this.g * 255) | 0;
  1664. var intB = (this.b * 255) | 0;
  1665. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1666. };
  1667. /**
  1668. * Computes a new Color3 converted from the current one to linear space
  1669. * @returns a new Color3 object
  1670. */
  1671. Color3.prototype.toLinearSpace = function () {
  1672. var convertedColor = new Color3();
  1673. this.toLinearSpaceToRef(convertedColor);
  1674. return convertedColor;
  1675. };
  1676. /**
  1677. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1678. * @param convertedColor defines the Color3 object where to store the linear space version
  1679. * @returns the unmodified Color3
  1680. */
  1681. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1682. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1683. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1684. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1685. return this;
  1686. };
  1687. /**
  1688. * Computes a new Color3 converted from the current one to gamma space
  1689. * @returns a new Color3 object
  1690. */
  1691. Color3.prototype.toGammaSpace = function () {
  1692. var convertedColor = new Color3();
  1693. this.toGammaSpaceToRef(convertedColor);
  1694. return convertedColor;
  1695. };
  1696. /**
  1697. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1698. * @param convertedColor defines the Color3 object where to store the gamma space version
  1699. * @returns the unmodified Color3
  1700. */
  1701. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1702. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1703. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1704. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1705. return this;
  1706. };
  1707. // Statics
  1708. /**
  1709. * Creates a new Color3 from the string containing valid hexadecimal values
  1710. * @param hex defines a string containing valid hexadecimal values
  1711. * @returns a new Color3 object
  1712. */
  1713. Color3.FromHexString = function (hex) {
  1714. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1715. return new Color3(0, 0, 0);
  1716. }
  1717. var r = parseInt(hex.substring(1, 3), 16);
  1718. var g = parseInt(hex.substring(3, 5), 16);
  1719. var b = parseInt(hex.substring(5, 7), 16);
  1720. return Color3.FromInts(r, g, b);
  1721. };
  1722. /**
  1723. * Creates a new Vector3 from the starting index of the given array
  1724. * @param array defines the source array
  1725. * @param offset defines an offset in the source array
  1726. * @returns a new Color3 object
  1727. */
  1728. Color3.FromArray = function (array, offset) {
  1729. if (offset === void 0) { offset = 0; }
  1730. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1731. };
  1732. /**
  1733. * Creates a new Color3 from integer values (< 256)
  1734. * @param r defines the red component to read from (value between 0 and 255)
  1735. * @param g defines the green component to read from (value between 0 and 255)
  1736. * @param b defines the blue component to read from (value between 0 and 255)
  1737. * @returns a new Color3 object
  1738. */
  1739. Color3.FromInts = function (r, g, b) {
  1740. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1741. };
  1742. /**
  1743. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1744. * @param start defines the start Color3 value
  1745. * @param end defines the end Color3 value
  1746. * @param amount defines the gradient value between start and end
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.Lerp = function (start, end, amount) {
  1750. var r = start.r + ((end.r - start.r) * amount);
  1751. var g = start.g + ((end.g - start.g) * amount);
  1752. var b = start.b + ((end.b - start.b) * amount);
  1753. return new Color3(r, g, b);
  1754. };
  1755. /**
  1756. * Returns a Color3 value containing a red color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Red = function () { return new Color3(1, 0, 0); };
  1760. /**
  1761. * Returns a Color3 value containing a green color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Green = function () { return new Color3(0, 1, 0); };
  1765. /**
  1766. * Returns a Color3 value containing a blue color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1770. /**
  1771. * Returns a Color3 value containing a black color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Black = function () { return new Color3(0, 0, 0); };
  1775. /**
  1776. * Returns a Color3 value containing a white color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.White = function () { return new Color3(1, 1, 1); };
  1780. /**
  1781. * Returns a Color3 value containing a purple color
  1782. * @returns a new Color3 object
  1783. */
  1784. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1785. /**
  1786. * Returns a Color3 value containing a magenta color
  1787. * @returns a new Color3 object
  1788. */
  1789. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1790. /**
  1791. * Returns a Color3 value containing a yellow color
  1792. * @returns a new Color3 object
  1793. */
  1794. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1795. /**
  1796. * Returns a Color3 value containing a gray color
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1800. /**
  1801. * Returns a Color3 value containing a teal color
  1802. * @returns a new Color3 object
  1803. */
  1804. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1805. /**
  1806. * Returns a Color3 value containing a random color
  1807. * @returns a new Color3 object
  1808. */
  1809. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1810. return Color3;
  1811. }());
  1812. BABYLON.Color3 = Color3;
  1813. /**
  1814. * Class used to hold a RBGA color
  1815. */
  1816. var Color4 = /** @class */ (function () {
  1817. /**
  1818. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1819. * @param r defines the red component (between 0 and 1, default is 0)
  1820. * @param g defines the green component (between 0 and 1, default is 0)
  1821. * @param b defines the blue component (between 0 and 1, default is 0)
  1822. * @param a defines the alpha component (between 0 and 1, default is 1)
  1823. */
  1824. function Color4(
  1825. /**
  1826. * Defines the red component (between 0 and 1, default is 0)
  1827. */
  1828. r,
  1829. /**
  1830. * Defines the green component (between 0 and 1, default is 0)
  1831. */
  1832. g,
  1833. /**
  1834. * Defines the blue component (between 0 and 1, default is 0)
  1835. */
  1836. b,
  1837. /**
  1838. * Defines the alpha component (between 0 and 1, default is 1)
  1839. */
  1840. a) {
  1841. if (r === void 0) { r = 0; }
  1842. if (g === void 0) { g = 0; }
  1843. if (b === void 0) { b = 0; }
  1844. if (a === void 0) { a = 1; }
  1845. this.r = r;
  1846. this.g = g;
  1847. this.b = b;
  1848. this.a = a;
  1849. }
  1850. // Operators
  1851. /**
  1852. * Adds in place the given Color4 values to the current Color4 object
  1853. * @param right defines the second operand
  1854. * @returns the current updated Color4 object
  1855. */
  1856. Color4.prototype.addInPlace = function (right) {
  1857. this.r += right.r;
  1858. this.g += right.g;
  1859. this.b += right.b;
  1860. this.a += right.a;
  1861. return this;
  1862. };
  1863. /**
  1864. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1865. * @returns the new array
  1866. */
  1867. Color4.prototype.asArray = function () {
  1868. var result = new Array();
  1869. this.toArray(result, 0);
  1870. return result;
  1871. };
  1872. /**
  1873. * Stores from the starting index in the given array the Color4 successive values
  1874. * @param array defines the array where to store the r,g,b components
  1875. * @param index defines an optional index in the target array to define where to start storing values
  1876. * @returns the current Color4 object
  1877. */
  1878. Color4.prototype.toArray = function (array, index) {
  1879. if (index === undefined) {
  1880. index = 0;
  1881. }
  1882. array[index] = this.r;
  1883. array[index + 1] = this.g;
  1884. array[index + 2] = this.b;
  1885. array[index + 3] = this.a;
  1886. return this;
  1887. };
  1888. /**
  1889. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1890. * @param right defines the second operand
  1891. * @returns a new Color4 object
  1892. */
  1893. Color4.prototype.add = function (right) {
  1894. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1895. };
  1896. /**
  1897. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1898. * @param right defines the second operand
  1899. * @returns a new Color4 object
  1900. */
  1901. Color4.prototype.subtract = function (right) {
  1902. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1903. };
  1904. /**
  1905. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1906. * @param right defines the second operand
  1907. * @param result defines the Color4 object where to store the result
  1908. * @returns the current Color4 object
  1909. */
  1910. Color4.prototype.subtractToRef = function (right, result) {
  1911. result.r = this.r - right.r;
  1912. result.g = this.g - right.g;
  1913. result.b = this.b - right.b;
  1914. result.a = this.a - right.a;
  1915. return this;
  1916. };
  1917. /**
  1918. * Creates a new Color4 with the current Color4 values multiplied by scale
  1919. * @param scale defines the scaling factor to apply
  1920. * @returns a new Color4 object
  1921. */
  1922. Color4.prototype.scale = function (scale) {
  1923. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1924. };
  1925. /**
  1926. * Multiplies the current Color4 values by scale and stores the result in "result"
  1927. * @param scale defines the scaling factor to apply
  1928. * @param result defines the Color4 object where to store the result
  1929. * @returns the current unmodified Color4
  1930. */
  1931. Color4.prototype.scaleToRef = function (scale, result) {
  1932. result.r = this.r * scale;
  1933. result.g = this.g * scale;
  1934. result.b = this.b * scale;
  1935. result.a = this.a * scale;
  1936. return this;
  1937. };
  1938. /**
  1939. * Scale the current Color4 values by a factor and add the result to a given Color4
  1940. * @param scale defines the scale factor
  1941. * @param result defines the Color4 object where to store the result
  1942. * @returns the unmodified current Color4
  1943. */
  1944. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1945. result.r += this.r * scale;
  1946. result.g += this.g * scale;
  1947. result.b += this.b * scale;
  1948. result.a += this.a * scale;
  1949. return this;
  1950. };
  1951. /**
  1952. * Clamps the rgb values by the min and max values and stores the result into "result"
  1953. * @param min defines minimum clamping value (default is 0)
  1954. * @param max defines maximum clamping value (default is 1)
  1955. * @param result defines color to store the result into.
  1956. * @returns the cuurent Color4
  1957. */
  1958. Color4.prototype.clampToRef = function (min, max, result) {
  1959. if (min === void 0) { min = 0; }
  1960. if (max === void 0) { max = 1; }
  1961. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1962. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1963. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1964. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1965. return this;
  1966. };
  1967. /**
  1968. * Multipy an Color4 value by another and return a new Color4 object
  1969. * @param color defines the Color4 value to multiply by
  1970. * @returns a new Color4 object
  1971. */
  1972. Color4.prototype.multiply = function (color) {
  1973. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1974. };
  1975. /**
  1976. * Multipy a Color4 value by another and push the result in a reference value
  1977. * @param color defines the Color4 value to multiply by
  1978. * @param result defines the Color4 to fill the result in
  1979. * @returns the result Color4
  1980. */
  1981. Color4.prototype.multiplyToRef = function (color, result) {
  1982. result.r = this.r * color.r;
  1983. result.g = this.g * color.g;
  1984. result.b = this.b * color.b;
  1985. result.a = this.a * color.a;
  1986. return result;
  1987. };
  1988. /**
  1989. * Creates a string with the Color4 current values
  1990. * @returns the string representation of the Color4 object
  1991. */
  1992. Color4.prototype.toString = function () {
  1993. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1994. };
  1995. /**
  1996. * Returns the string "Color4"
  1997. * @returns "Color4"
  1998. */
  1999. Color4.prototype.getClassName = function () {
  2000. return "Color4";
  2001. };
  2002. /**
  2003. * Compute the Color4 hash code
  2004. * @returns an unique number that can be used to hash Color4 objects
  2005. */
  2006. Color4.prototype.getHashCode = function () {
  2007. var hash = this.r || 0;
  2008. hash = (hash * 397) ^ (this.g || 0);
  2009. hash = (hash * 397) ^ (this.b || 0);
  2010. hash = (hash * 397) ^ (this.a || 0);
  2011. return hash;
  2012. };
  2013. /**
  2014. * Creates a new Color4 copied from the current one
  2015. * @returns a new Color4 object
  2016. */
  2017. Color4.prototype.clone = function () {
  2018. return new Color4(this.r, this.g, this.b, this.a);
  2019. };
  2020. /**
  2021. * Copies the given Color4 values into the current one
  2022. * @param source defines the source Color4 object
  2023. * @returns the current updated Color4 object
  2024. */
  2025. Color4.prototype.copyFrom = function (source) {
  2026. this.r = source.r;
  2027. this.g = source.g;
  2028. this.b = source.b;
  2029. this.a = source.a;
  2030. return this;
  2031. };
  2032. /**
  2033. * Copies the given float values into the current one
  2034. * @param r defines the red component to read from
  2035. * @param g defines the green component to read from
  2036. * @param b defines the blue component to read from
  2037. * @param a defines the alpha component to read from
  2038. * @returns the current updated Color4 object
  2039. */
  2040. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2041. this.r = r;
  2042. this.g = g;
  2043. this.b = b;
  2044. this.a = a;
  2045. return this;
  2046. };
  2047. /**
  2048. * Copies the given float values into the current one
  2049. * @param r defines the red component to read from
  2050. * @param g defines the green component to read from
  2051. * @param b defines the blue component to read from
  2052. * @param a defines the alpha component to read from
  2053. * @returns the current updated Color4 object
  2054. */
  2055. Color4.prototype.set = function (r, g, b, a) {
  2056. return this.copyFromFloats(r, g, b, a);
  2057. };
  2058. /**
  2059. * Compute the Color4 hexadecimal code as a string
  2060. * @returns a string containing the hexadecimal representation of the Color4 object
  2061. */
  2062. Color4.prototype.toHexString = function () {
  2063. var intR = (this.r * 255) | 0;
  2064. var intG = (this.g * 255) | 0;
  2065. var intB = (this.b * 255) | 0;
  2066. var intA = (this.a * 255) | 0;
  2067. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2068. };
  2069. /**
  2070. * Computes a new Color4 converted from the current one to linear space
  2071. * @returns a new Color4 object
  2072. */
  2073. Color4.prototype.toLinearSpace = function () {
  2074. var convertedColor = new Color4();
  2075. this.toLinearSpaceToRef(convertedColor);
  2076. return convertedColor;
  2077. };
  2078. /**
  2079. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2080. * @param convertedColor defines the Color4 object where to store the linear space version
  2081. * @returns the unmodified Color4
  2082. */
  2083. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2084. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2085. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2086. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2087. convertedColor.a = this.a;
  2088. return this;
  2089. };
  2090. /**
  2091. * Computes a new Color4 converted from the current one to gamma space
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.prototype.toGammaSpace = function () {
  2095. var convertedColor = new Color4();
  2096. this.toGammaSpaceToRef(convertedColor);
  2097. return convertedColor;
  2098. };
  2099. /**
  2100. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2101. * @param convertedColor defines the Color4 object where to store the gamma space version
  2102. * @returns the unmodified Color4
  2103. */
  2104. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2105. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2106. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2107. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2108. convertedColor.a = this.a;
  2109. return this;
  2110. };
  2111. // Statics
  2112. /**
  2113. * Creates a new Color4 from the string containing valid hexadecimal values
  2114. * @param hex defines a string containing valid hexadecimal values
  2115. * @returns a new Color4 object
  2116. */
  2117. Color4.FromHexString = function (hex) {
  2118. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2119. return new Color4(0.0, 0.0, 0.0, 0.0);
  2120. }
  2121. var r = parseInt(hex.substring(1, 3), 16);
  2122. var g = parseInt(hex.substring(3, 5), 16);
  2123. var b = parseInt(hex.substring(5, 7), 16);
  2124. var a = parseInt(hex.substring(7, 9), 16);
  2125. return Color4.FromInts(r, g, b, a);
  2126. };
  2127. /**
  2128. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2129. * @param left defines the start value
  2130. * @param right defines the end value
  2131. * @param amount defines the gradient factor
  2132. * @returns a new Color4 object
  2133. */
  2134. Color4.Lerp = function (left, right, amount) {
  2135. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2136. Color4.LerpToRef(left, right, amount, result);
  2137. return result;
  2138. };
  2139. /**
  2140. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2141. * @param left defines the start value
  2142. * @param right defines the end value
  2143. * @param amount defines the gradient factor
  2144. * @param result defines the Color4 object where to store data
  2145. */
  2146. Color4.LerpToRef = function (left, right, amount, result) {
  2147. result.r = left.r + (right.r - left.r) * amount;
  2148. result.g = left.g + (right.g - left.g) * amount;
  2149. result.b = left.b + (right.b - left.b) * amount;
  2150. result.a = left.a + (right.a - left.a) * amount;
  2151. };
  2152. /**
  2153. * Creates a new Color4 from the starting index element of the given array
  2154. * @param array defines the source array to read from
  2155. * @param offset defines the offset in the source array
  2156. * @returns a new Color4 object
  2157. */
  2158. Color4.FromArray = function (array, offset) {
  2159. if (offset === void 0) { offset = 0; }
  2160. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2161. };
  2162. /**
  2163. * Creates a new Color3 from integer values (< 256)
  2164. * @param r defines the red component to read from (value between 0 and 255)
  2165. * @param g defines the green component to read from (value between 0 and 255)
  2166. * @param b defines the blue component to read from (value between 0 and 255)
  2167. * @param a defines the alpha component to read from (value between 0 and 255)
  2168. * @returns a new Color3 object
  2169. */
  2170. Color4.FromInts = function (r, g, b, a) {
  2171. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2172. };
  2173. /**
  2174. * Check the content of a given array and convert it to an array containing RGBA data
  2175. * If the original array was already containing count * 4 values then it is returned directly
  2176. * @param colors defines the array to check
  2177. * @param count defines the number of RGBA data to expect
  2178. * @returns an array containing count * 4 values (RGBA)
  2179. */
  2180. Color4.CheckColors4 = function (colors, count) {
  2181. // Check if color3 was used
  2182. if (colors.length === count * 3) {
  2183. var colors4 = [];
  2184. for (var index = 0; index < colors.length; index += 3) {
  2185. var newIndex = (index / 3) * 4;
  2186. colors4[newIndex] = colors[index];
  2187. colors4[newIndex + 1] = colors[index + 1];
  2188. colors4[newIndex + 2] = colors[index + 2];
  2189. colors4[newIndex + 3] = 1.0;
  2190. }
  2191. return colors4;
  2192. }
  2193. return colors;
  2194. };
  2195. return Color4;
  2196. }());
  2197. BABYLON.Color4 = Color4;
  2198. /**
  2199. * Class representing a vector containing 2 coordinates
  2200. */
  2201. var Vector2 = /** @class */ (function () {
  2202. /**
  2203. * Creates a new Vector2 from the given x and y coordinates
  2204. * @param x defines the first coordinate
  2205. * @param y defines the second coordinate
  2206. */
  2207. function Vector2(
  2208. /** defines the first coordinate */
  2209. x,
  2210. /** defines the second coordinate */
  2211. y) {
  2212. this.x = x;
  2213. this.y = y;
  2214. }
  2215. /**
  2216. * Gets a string with the Vector2 coordinates
  2217. * @returns a string with the Vector2 coordinates
  2218. */
  2219. Vector2.prototype.toString = function () {
  2220. return "{X: " + this.x + " Y:" + this.y + "}";
  2221. };
  2222. /**
  2223. * Gets class name
  2224. * @returns the string "Vector2"
  2225. */
  2226. Vector2.prototype.getClassName = function () {
  2227. return "Vector2";
  2228. };
  2229. /**
  2230. * Gets current vector hash code
  2231. * @returns the Vector2 hash code as a number
  2232. */
  2233. Vector2.prototype.getHashCode = function () {
  2234. var hash = this.x || 0;
  2235. hash = (hash * 397) ^ (this.y || 0);
  2236. return hash;
  2237. };
  2238. // Operators
  2239. /**
  2240. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2241. * @param array defines the source array
  2242. * @param index defines the offset in source array
  2243. * @returns the current Vector2
  2244. */
  2245. Vector2.prototype.toArray = function (array, index) {
  2246. if (index === void 0) { index = 0; }
  2247. array[index] = this.x;
  2248. array[index + 1] = this.y;
  2249. return this;
  2250. };
  2251. /**
  2252. * Copy the current vector to an array
  2253. * @returns a new array with 2 elements: the Vector2 coordinates.
  2254. */
  2255. Vector2.prototype.asArray = function () {
  2256. var result = new Array();
  2257. this.toArray(result, 0);
  2258. return result;
  2259. };
  2260. /**
  2261. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2262. * @param source defines the source Vector2
  2263. * @returns the current updated Vector2
  2264. */
  2265. Vector2.prototype.copyFrom = function (source) {
  2266. this.x = source.x;
  2267. this.y = source.y;
  2268. return this;
  2269. };
  2270. /**
  2271. * Sets the Vector2 coordinates with the given floats
  2272. * @param x defines the first coordinate
  2273. * @param y defines the second coordinate
  2274. * @returns the current updated Vector2
  2275. */
  2276. Vector2.prototype.copyFromFloats = function (x, y) {
  2277. this.x = x;
  2278. this.y = y;
  2279. return this;
  2280. };
  2281. /**
  2282. * Sets the Vector2 coordinates with the given floats
  2283. * @param x defines the first coordinate
  2284. * @param y defines the second coordinate
  2285. * @returns the current updated Vector2
  2286. */
  2287. Vector2.prototype.set = function (x, y) {
  2288. return this.copyFromFloats(x, y);
  2289. };
  2290. /**
  2291. * Add another vector with the current one
  2292. * @param otherVector defines the other vector
  2293. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2294. */
  2295. Vector2.prototype.add = function (otherVector) {
  2296. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2297. };
  2298. /**
  2299. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2300. * @param otherVector defines the other vector
  2301. * @param result defines the target vector
  2302. * @returns the unmodified current Vector2
  2303. */
  2304. Vector2.prototype.addToRef = function (otherVector, result) {
  2305. result.x = this.x + otherVector.x;
  2306. result.y = this.y + otherVector.y;
  2307. return this;
  2308. };
  2309. /**
  2310. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2311. * @param otherVector defines the other vector
  2312. * @returns the current updated Vector2
  2313. */
  2314. Vector2.prototype.addInPlace = function (otherVector) {
  2315. this.x += otherVector.x;
  2316. this.y += otherVector.y;
  2317. return this;
  2318. };
  2319. /**
  2320. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2321. * @param otherVector defines the other vector
  2322. * @returns a new Vector2
  2323. */
  2324. Vector2.prototype.addVector3 = function (otherVector) {
  2325. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2326. };
  2327. /**
  2328. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2329. * @param otherVector defines the other vector
  2330. * @returns a new Vector2
  2331. */
  2332. Vector2.prototype.subtract = function (otherVector) {
  2333. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2334. };
  2335. /**
  2336. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2337. * @param otherVector defines the other vector
  2338. * @param result defines the target vector
  2339. * @returns the unmodified current Vector2
  2340. */
  2341. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2342. result.x = this.x - otherVector.x;
  2343. result.y = this.y - otherVector.y;
  2344. return this;
  2345. };
  2346. /**
  2347. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2348. * @param otherVector defines the other vector
  2349. * @returns the current updated Vector2
  2350. */
  2351. Vector2.prototype.subtractInPlace = function (otherVector) {
  2352. this.x -= otherVector.x;
  2353. this.y -= otherVector.y;
  2354. return this;
  2355. };
  2356. /**
  2357. * Multiplies in place the current Vector2 coordinates by the given ones
  2358. * @param otherVector defines the other vector
  2359. * @returns the current updated Vector2
  2360. */
  2361. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2362. this.x *= otherVector.x;
  2363. this.y *= otherVector.y;
  2364. return this;
  2365. };
  2366. /**
  2367. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2368. * @param otherVector defines the other vector
  2369. * @returns a new Vector2
  2370. */
  2371. Vector2.prototype.multiply = function (otherVector) {
  2372. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2373. };
  2374. /**
  2375. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2376. * @param otherVector defines the other vector
  2377. * @param result defines the target vector
  2378. * @returns the unmodified current Vector2
  2379. */
  2380. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2381. result.x = this.x * otherVector.x;
  2382. result.y = this.y * otherVector.y;
  2383. return this;
  2384. };
  2385. /**
  2386. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2387. * @param x defines the first coordinate
  2388. * @param y defines the second coordinate
  2389. * @returns a new Vector2
  2390. */
  2391. Vector2.prototype.multiplyByFloats = function (x, y) {
  2392. return new Vector2(this.x * x, this.y * y);
  2393. };
  2394. /**
  2395. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2396. * @param otherVector defines the other vector
  2397. * @returns a new Vector2
  2398. */
  2399. Vector2.prototype.divide = function (otherVector) {
  2400. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2401. };
  2402. /**
  2403. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2404. * @param otherVector defines the other vector
  2405. * @param result defines the target vector
  2406. * @returns the unmodified current Vector2
  2407. */
  2408. Vector2.prototype.divideToRef = function (otherVector, result) {
  2409. result.x = this.x / otherVector.x;
  2410. result.y = this.y / otherVector.y;
  2411. return this;
  2412. };
  2413. /**
  2414. * Divides the current Vector3 coordinates by the given ones
  2415. * @param otherVector defines the other vector
  2416. * @returns the current updated Vector2
  2417. */
  2418. Vector2.prototype.divideInPlace = function (otherVector) {
  2419. return this.divideToRef(otherVector, this);
  2420. };
  2421. /**
  2422. * Gets a new Vector2 with current Vector2 negated coordinates
  2423. * @returns a new Vector2
  2424. */
  2425. Vector2.prototype.negate = function () {
  2426. return new Vector2(-this.x, -this.y);
  2427. };
  2428. /**
  2429. * Multiply the Vector2 coordinates by scale
  2430. * @param scale defines the scaling factor
  2431. * @returns the current updated Vector2
  2432. */
  2433. Vector2.prototype.scaleInPlace = function (scale) {
  2434. this.x *= scale;
  2435. this.y *= scale;
  2436. return this;
  2437. };
  2438. /**
  2439. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2440. * @param scale defines the scaling factor
  2441. * @returns a new Vector2
  2442. */
  2443. Vector2.prototype.scale = function (scale) {
  2444. var result = new Vector2(0, 0);
  2445. this.scaleToRef(scale, result);
  2446. return result;
  2447. };
  2448. /**
  2449. * Scale the current Vector2 values by a factor to a given Vector2
  2450. * @param scale defines the scale factor
  2451. * @param result defines the Vector2 object where to store the result
  2452. * @returns the unmodified current Vector2
  2453. */
  2454. Vector2.prototype.scaleToRef = function (scale, result) {
  2455. result.x = this.x * scale;
  2456. result.y = this.y * scale;
  2457. return this;
  2458. };
  2459. /**
  2460. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2461. * @param scale defines the scale factor
  2462. * @param result defines the Vector2 object where to store the result
  2463. * @returns the unmodified current Vector2
  2464. */
  2465. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2466. result.x += this.x * scale;
  2467. result.y += this.y * scale;
  2468. return this;
  2469. };
  2470. /**
  2471. * Gets a boolean if two vectors are equals
  2472. * @param otherVector defines the other vector
  2473. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2474. */
  2475. Vector2.prototype.equals = function (otherVector) {
  2476. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2477. };
  2478. /**
  2479. * Gets a boolean if two vectors are equals (using an epsilon value)
  2480. * @param otherVector defines the other vector
  2481. * @param epsilon defines the minimal distance to consider equality
  2482. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2483. */
  2484. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2485. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2486. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2487. };
  2488. // Properties
  2489. /**
  2490. * Gets the length of the vector
  2491. * @returns the vector length (float)
  2492. */
  2493. Vector2.prototype.length = function () {
  2494. return Math.sqrt(this.x * this.x + this.y * this.y);
  2495. };
  2496. /**
  2497. * Gets the vector squared length
  2498. * @returns the vector squared length (float)
  2499. */
  2500. Vector2.prototype.lengthSquared = function () {
  2501. return (this.x * this.x + this.y * this.y);
  2502. };
  2503. // Methods
  2504. /**
  2505. * Normalize the vector
  2506. * @returns the current updated Vector2
  2507. */
  2508. Vector2.prototype.normalize = function () {
  2509. var len = this.length();
  2510. if (len === 0)
  2511. return this;
  2512. var num = 1.0 / len;
  2513. this.x *= num;
  2514. this.y *= num;
  2515. return this;
  2516. };
  2517. /**
  2518. * Gets a new Vector2 copied from the Vector2
  2519. * @returns a new Vector2
  2520. */
  2521. Vector2.prototype.clone = function () {
  2522. return new Vector2(this.x, this.y);
  2523. };
  2524. // Statics
  2525. /**
  2526. * Gets a new Vector2(0, 0)
  2527. * @returns a new Vector2
  2528. */
  2529. Vector2.Zero = function () {
  2530. return new Vector2(0, 0);
  2531. };
  2532. /**
  2533. * Gets a new Vector2(1, 1)
  2534. * @returns a new Vector2
  2535. */
  2536. Vector2.One = function () {
  2537. return new Vector2(1, 1);
  2538. };
  2539. /**
  2540. * Gets a new Vector2 set from the given index element of the given array
  2541. * @param array defines the data source
  2542. * @param offset defines the offset in the data source
  2543. * @returns a new Vector2
  2544. */
  2545. Vector2.FromArray = function (array, offset) {
  2546. if (offset === void 0) { offset = 0; }
  2547. return new Vector2(array[offset], array[offset + 1]);
  2548. };
  2549. /**
  2550. * Sets "result" from the given index element of the given array
  2551. * @param array defines the data source
  2552. * @param offset defines the offset in the data source
  2553. * @param result defines the target vector
  2554. */
  2555. Vector2.FromArrayToRef = function (array, offset, result) {
  2556. result.x = array[offset];
  2557. result.y = array[offset + 1];
  2558. };
  2559. /**
  2560. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2561. * @param value1 defines 1st point of control
  2562. * @param value2 defines 2nd point of control
  2563. * @param value3 defines 3rd point of control
  2564. * @param value4 defines 4th point of control
  2565. * @param amount defines the interpolation factor
  2566. * @returns a new Vector2
  2567. */
  2568. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2569. var squared = amount * amount;
  2570. var cubed = amount * squared;
  2571. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2572. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2573. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2574. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2575. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2576. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2577. return new Vector2(x, y);
  2578. };
  2579. /**
  2580. * 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".
  2581. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2582. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2583. * @param value defines the value to clamp
  2584. * @param min defines the lower limit
  2585. * @param max defines the upper limit
  2586. * @returns a new Vector2
  2587. */
  2588. Vector2.Clamp = function (value, min, max) {
  2589. var x = value.x;
  2590. x = (x > max.x) ? max.x : x;
  2591. x = (x < min.x) ? min.x : x;
  2592. var y = value.y;
  2593. y = (y > max.y) ? max.y : y;
  2594. y = (y < min.y) ? min.y : y;
  2595. return new Vector2(x, y);
  2596. };
  2597. /**
  2598. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2599. * @param value1 defines the 1st control point
  2600. * @param tangent1 defines the outgoing tangent
  2601. * @param value2 defines the 2nd control point
  2602. * @param tangent2 defines the incoming tangent
  2603. * @param amount defines the interpolation factor
  2604. * @returns a new Vector2
  2605. */
  2606. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2607. var squared = amount * amount;
  2608. var cubed = amount * squared;
  2609. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2610. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2611. var part3 = (cubed - (2.0 * squared)) + amount;
  2612. var part4 = cubed - squared;
  2613. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2614. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2615. return new Vector2(x, y);
  2616. };
  2617. /**
  2618. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2619. * @param start defines the start vector
  2620. * @param end defines the end vector
  2621. * @param amount defines the interpolation factor
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.Lerp = function (start, end, amount) {
  2625. var x = start.x + ((end.x - start.x) * amount);
  2626. var y = start.y + ((end.y - start.y) * amount);
  2627. return new Vector2(x, y);
  2628. };
  2629. /**
  2630. * Gets the dot product of the vector "left" and the vector "right"
  2631. * @param left defines first vector
  2632. * @param right defines second vector
  2633. * @returns the dot product (float)
  2634. */
  2635. Vector2.Dot = function (left, right) {
  2636. return left.x * right.x + left.y * right.y;
  2637. };
  2638. /**
  2639. * Returns a new Vector2 equal to the normalized given vector
  2640. * @param vector defines the vector to normalize
  2641. * @returns a new Vector2
  2642. */
  2643. Vector2.Normalize = function (vector) {
  2644. var newVector = vector.clone();
  2645. newVector.normalize();
  2646. return newVector;
  2647. };
  2648. /**
  2649. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2650. * @param left defines 1st vector
  2651. * @param right defines 2nd vector
  2652. * @returns a new Vector2
  2653. */
  2654. Vector2.Minimize = function (left, right) {
  2655. var x = (left.x < right.x) ? left.x : right.x;
  2656. var y = (left.y < right.y) ? left.y : right.y;
  2657. return new Vector2(x, y);
  2658. };
  2659. /**
  2660. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2661. * @param left defines 1st vector
  2662. * @param right defines 2nd vector
  2663. * @returns a new Vector2
  2664. */
  2665. Vector2.Maximize = function (left, right) {
  2666. var x = (left.x > right.x) ? left.x : right.x;
  2667. var y = (left.y > right.y) ? left.y : right.y;
  2668. return new Vector2(x, y);
  2669. };
  2670. /**
  2671. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2672. * @param vector defines the vector to transform
  2673. * @param transformation defines the matrix to apply
  2674. * @returns a new Vector2
  2675. */
  2676. Vector2.Transform = function (vector, transformation) {
  2677. var r = Vector2.Zero();
  2678. Vector2.TransformToRef(vector, transformation, r);
  2679. return r;
  2680. };
  2681. /**
  2682. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2683. * @param vector defines the vector to transform
  2684. * @param transformation defines the matrix to apply
  2685. * @param result defines the target vector
  2686. */
  2687. Vector2.TransformToRef = function (vector, transformation, result) {
  2688. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2689. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2690. result.x = x;
  2691. result.y = y;
  2692. };
  2693. /**
  2694. * Determines if a given vector is included in a triangle
  2695. * @param p defines the vector to test
  2696. * @param p0 defines 1st triangle point
  2697. * @param p1 defines 2nd triangle point
  2698. * @param p2 defines 3rd triangle point
  2699. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2700. */
  2701. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2702. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2703. var sign = a < 0 ? -1 : 1;
  2704. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2705. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2706. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2707. };
  2708. /**
  2709. * Gets the distance between the vectors "value1" and "value2"
  2710. * @param value1 defines first vector
  2711. * @param value2 defines second vector
  2712. * @returns the distance between vectors
  2713. */
  2714. Vector2.Distance = function (value1, value2) {
  2715. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2716. };
  2717. /**
  2718. * Returns the squared distance between the vectors "value1" and "value2"
  2719. * @param value1 defines first vector
  2720. * @param value2 defines second vector
  2721. * @returns the squared distance between vectors
  2722. */
  2723. Vector2.DistanceSquared = function (value1, value2) {
  2724. var x = value1.x - value2.x;
  2725. var y = value1.y - value2.y;
  2726. return (x * x) + (y * y);
  2727. };
  2728. /**
  2729. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2730. * @param value1 defines first vector
  2731. * @param value2 defines second vector
  2732. * @returns a new Vector2
  2733. */
  2734. Vector2.Center = function (value1, value2) {
  2735. var center = value1.add(value2);
  2736. center.scaleInPlace(0.5);
  2737. return center;
  2738. };
  2739. /**
  2740. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2741. * @param p defines the middle point
  2742. * @param segA defines one point of the segment
  2743. * @param segB defines the other point of the segment
  2744. * @returns the shortest distance
  2745. */
  2746. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2747. var l2 = Vector2.DistanceSquared(segA, segB);
  2748. if (l2 === 0.0) {
  2749. return Vector2.Distance(p, segA);
  2750. }
  2751. var v = segB.subtract(segA);
  2752. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2753. var proj = segA.add(v.multiplyByFloats(t, t));
  2754. return Vector2.Distance(p, proj);
  2755. };
  2756. return Vector2;
  2757. }());
  2758. BABYLON.Vector2 = Vector2;
  2759. /**
  2760. * Classed used to store (x,y,z) vector representation
  2761. * A Vector3 is the main object used in 3D geometry
  2762. * It can represent etiher the coordinates of a point the space, either a direction
  2763. * Reminder: Babylon.js uses a left handed forward facing system
  2764. */
  2765. var Vector3 = /** @class */ (function () {
  2766. /**
  2767. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2768. * @param x defines the first coordinates (on X axis)
  2769. * @param y defines the second coordinates (on Y axis)
  2770. * @param z defines the third coordinates (on Z axis)
  2771. */
  2772. function Vector3(
  2773. /**
  2774. * Defines the first coordinates (on X axis)
  2775. */
  2776. x,
  2777. /**
  2778. * Defines the second coordinates (on Y axis)
  2779. */
  2780. y,
  2781. /**
  2782. * Defines the third coordinates (on Z axis)
  2783. */
  2784. z) {
  2785. this.x = x;
  2786. this.y = y;
  2787. this.z = z;
  2788. }
  2789. /**
  2790. * Creates a string representation of the Vector3
  2791. * @returns a string with the Vector3 coordinates.
  2792. */
  2793. Vector3.prototype.toString = function () {
  2794. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2795. };
  2796. /**
  2797. * Gets the class name
  2798. * @returns the string "Vector3"
  2799. */
  2800. Vector3.prototype.getClassName = function () {
  2801. return "Vector3";
  2802. };
  2803. /**
  2804. * Creates the Vector3 hash code
  2805. * @returns a number which tends to be unique between Vector3 instances
  2806. */
  2807. Vector3.prototype.getHashCode = function () {
  2808. var hash = this.x || 0;
  2809. hash = (hash * 397) ^ (this.y || 0);
  2810. hash = (hash * 397) ^ (this.z || 0);
  2811. return hash;
  2812. };
  2813. // Operators
  2814. /**
  2815. * Creates an array containing three elements : the coordinates of the Vector3
  2816. * @returns a new array of numbers
  2817. */
  2818. Vector3.prototype.asArray = function () {
  2819. var result = [];
  2820. this.toArray(result, 0);
  2821. return result;
  2822. };
  2823. /**
  2824. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2825. * @param array defines the destination array
  2826. * @param index defines the offset in the destination array
  2827. * @returns the current Vector3
  2828. */
  2829. Vector3.prototype.toArray = function (array, index) {
  2830. if (index === void 0) { index = 0; }
  2831. array[index] = this.x;
  2832. array[index + 1] = this.y;
  2833. array[index + 2] = this.z;
  2834. return this;
  2835. };
  2836. /**
  2837. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2838. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2839. */
  2840. Vector3.prototype.toQuaternion = function () {
  2841. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2842. };
  2843. /**
  2844. * Adds the given vector to the current Vector3
  2845. * @param otherVector defines the second operand
  2846. * @returns the current updated Vector3
  2847. */
  2848. Vector3.prototype.addInPlace = function (otherVector) {
  2849. this.x += otherVector.x;
  2850. this.y += otherVector.y;
  2851. this.z += otherVector.z;
  2852. return this;
  2853. };
  2854. /**
  2855. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2856. * @param otherVector defines the second operand
  2857. * @returns the resulting Vector3
  2858. */
  2859. Vector3.prototype.add = function (otherVector) {
  2860. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2861. };
  2862. /**
  2863. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2864. * @param otherVector defines the second operand
  2865. * @param result defines the Vector3 object where to store the result
  2866. * @returns the current Vector3
  2867. */
  2868. Vector3.prototype.addToRef = function (otherVector, result) {
  2869. result.x = this.x + otherVector.x;
  2870. result.y = this.y + otherVector.y;
  2871. result.z = this.z + otherVector.z;
  2872. return this;
  2873. };
  2874. /**
  2875. * Subtract the given vector from the current Vector3
  2876. * @param otherVector defines the second operand
  2877. * @returns the current updated Vector3
  2878. */
  2879. Vector3.prototype.subtractInPlace = function (otherVector) {
  2880. this.x -= otherVector.x;
  2881. this.y -= otherVector.y;
  2882. this.z -= otherVector.z;
  2883. return this;
  2884. };
  2885. /**
  2886. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2887. * @param otherVector defines the second operand
  2888. * @returns the resulting Vector3
  2889. */
  2890. Vector3.prototype.subtract = function (otherVector) {
  2891. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2892. };
  2893. /**
  2894. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2895. * @param otherVector defines the second operand
  2896. * @param result defines the Vector3 object where to store the result
  2897. * @returns the current Vector3
  2898. */
  2899. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2900. result.x = this.x - otherVector.x;
  2901. result.y = this.y - otherVector.y;
  2902. result.z = this.z - otherVector.z;
  2903. return this;
  2904. };
  2905. /**
  2906. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2907. * @param x defines the x coordinate of the operand
  2908. * @param y defines the y coordinate of the operand
  2909. * @param z defines the z coordinate of the operand
  2910. * @returns the resulting Vector3
  2911. */
  2912. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2913. return new Vector3(this.x - x, this.y - y, this.z - z);
  2914. };
  2915. /**
  2916. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2917. * @param x defines the x coordinate of the operand
  2918. * @param y defines the y coordinate of the operand
  2919. * @param z defines the z coordinate of the operand
  2920. * @param result defines the Vector3 object where to store the result
  2921. * @returns the current Vector3
  2922. */
  2923. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2924. result.x = this.x - x;
  2925. result.y = this.y - y;
  2926. result.z = this.z - z;
  2927. return this;
  2928. };
  2929. /**
  2930. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2931. * @returns a new Vector3
  2932. */
  2933. Vector3.prototype.negate = function () {
  2934. return new Vector3(-this.x, -this.y, -this.z);
  2935. };
  2936. /**
  2937. * Multiplies the Vector3 coordinates by the float "scale"
  2938. * @param scale defines the multiplier factor
  2939. * @returns the current updated Vector3
  2940. */
  2941. Vector3.prototype.scaleInPlace = function (scale) {
  2942. this.x *= scale;
  2943. this.y *= scale;
  2944. this.z *= scale;
  2945. return this;
  2946. };
  2947. /**
  2948. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2949. * @param scale defines the multiplier factor
  2950. * @returns a new Vector3
  2951. */
  2952. Vector3.prototype.scale = function (scale) {
  2953. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2954. };
  2955. /**
  2956. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2957. * @param scale defines the multiplier factor
  2958. * @param result defines the Vector3 object where to store the result
  2959. * @returns the current Vector3
  2960. */
  2961. Vector3.prototype.scaleToRef = function (scale, result) {
  2962. result.x = this.x * scale;
  2963. result.y = this.y * scale;
  2964. result.z = this.z * scale;
  2965. return this;
  2966. };
  2967. /**
  2968. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2969. * @param scale defines the scale factor
  2970. * @param result defines the Vector3 object where to store the result
  2971. * @returns the unmodified current Vector3
  2972. */
  2973. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2974. result.x += this.x * scale;
  2975. result.y += this.y * scale;
  2976. result.z += this.z * scale;
  2977. return this;
  2978. };
  2979. /**
  2980. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2981. * @param otherVector defines the second operand
  2982. * @returns true if both vectors are equals
  2983. */
  2984. Vector3.prototype.equals = function (otherVector) {
  2985. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2986. };
  2987. /**
  2988. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2989. * @param otherVector defines the second operand
  2990. * @param epsilon defines the minimal distance to define values as equals
  2991. * @returns true if both vectors are distant less than epsilon
  2992. */
  2993. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2994. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2995. 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);
  2996. };
  2997. /**
  2998. * Returns true if the current Vector3 coordinates equals the given floats
  2999. * @param x defines the x coordinate of the operand
  3000. * @param y defines the y coordinate of the operand
  3001. * @param z defines the z coordinate of the operand
  3002. * @returns true if both vectors are equals
  3003. */
  3004. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3005. return this.x === x && this.y === y && this.z === z;
  3006. };
  3007. /**
  3008. * Multiplies the current Vector3 coordinates by the given ones
  3009. * @param otherVector defines the second operand
  3010. * @returns the current updated Vector3
  3011. */
  3012. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3013. this.x *= otherVector.x;
  3014. this.y *= otherVector.y;
  3015. this.z *= otherVector.z;
  3016. return this;
  3017. };
  3018. /**
  3019. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3020. * @param otherVector defines the second operand
  3021. * @returns the new Vector3
  3022. */
  3023. Vector3.prototype.multiply = function (otherVector) {
  3024. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3025. };
  3026. /**
  3027. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3028. * @param otherVector defines the second operand
  3029. * @param result defines the Vector3 object where to store the result
  3030. * @returns the current Vector3
  3031. */
  3032. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3033. result.x = this.x * otherVector.x;
  3034. result.y = this.y * otherVector.y;
  3035. result.z = this.z * otherVector.z;
  3036. return this;
  3037. };
  3038. /**
  3039. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3040. * @param x defines the x coordinate of the operand
  3041. * @param y defines the y coordinate of the operand
  3042. * @param z defines the z coordinate of the operand
  3043. * @returns the new Vector3
  3044. */
  3045. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3046. return new Vector3(this.x * x, this.y * y, this.z * z);
  3047. };
  3048. /**
  3049. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3050. * @param otherVector defines the second operand
  3051. * @returns the new Vector3
  3052. */
  3053. Vector3.prototype.divide = function (otherVector) {
  3054. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3055. };
  3056. /**
  3057. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3058. * @param otherVector defines the second operand
  3059. * @param result defines the Vector3 object where to store the result
  3060. * @returns the current Vector3
  3061. */
  3062. Vector3.prototype.divideToRef = function (otherVector, result) {
  3063. result.x = this.x / otherVector.x;
  3064. result.y = this.y / otherVector.y;
  3065. result.z = this.z / otherVector.z;
  3066. return this;
  3067. };
  3068. /**
  3069. * Divides the current Vector3 coordinates by the given ones.
  3070. * @param otherVector defines the second operand
  3071. * @returns the current updated Vector3
  3072. */
  3073. Vector3.prototype.divideInPlace = function (otherVector) {
  3074. return this.divideToRef(otherVector, this);
  3075. };
  3076. /**
  3077. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3078. * @param other defines the second operand
  3079. * @returns the current updated Vector3
  3080. */
  3081. Vector3.prototype.minimizeInPlace = function (other) {
  3082. if (other.x < this.x)
  3083. this.x = other.x;
  3084. if (other.y < this.y)
  3085. this.y = other.y;
  3086. if (other.z < this.z)
  3087. this.z = other.z;
  3088. return this;
  3089. };
  3090. /**
  3091. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3092. * @param other defines the second operand
  3093. * @returns the current updated Vector3
  3094. */
  3095. Vector3.prototype.maximizeInPlace = function (other) {
  3096. if (other.x > this.x)
  3097. this.x = other.x;
  3098. if (other.y > this.y)
  3099. this.y = other.y;
  3100. if (other.z > this.z)
  3101. this.z = other.z;
  3102. return this;
  3103. };
  3104. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3105. /**
  3106. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3107. */
  3108. get: function () {
  3109. var absX = Math.abs(this.x);
  3110. var absY = Math.abs(this.y);
  3111. if (absX !== absY) {
  3112. return true;
  3113. }
  3114. var absZ = Math.abs(this.z);
  3115. if (absX !== absZ) {
  3116. return true;
  3117. }
  3118. if (absY !== absZ) {
  3119. return true;
  3120. }
  3121. return false;
  3122. },
  3123. enumerable: true,
  3124. configurable: true
  3125. });
  3126. // Properties
  3127. /**
  3128. * Gets the length of the Vector3
  3129. * @returns the length of the Vecto3
  3130. */
  3131. Vector3.prototype.length = function () {
  3132. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3133. };
  3134. /**
  3135. * Gets the squared length of the Vector3
  3136. * @returns squared length of the Vector3
  3137. */
  3138. Vector3.prototype.lengthSquared = function () {
  3139. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3140. };
  3141. /**
  3142. * Normalize the current Vector3.
  3143. * Please note that this is an in place operation.
  3144. * @returns the current updated Vector3
  3145. */
  3146. Vector3.prototype.normalize = function () {
  3147. var len = this.length();
  3148. if (len === 0 || len === 1.0)
  3149. return this;
  3150. var num = 1.0 / len;
  3151. this.x *= num;
  3152. this.y *= num;
  3153. this.z *= num;
  3154. return this;
  3155. };
  3156. /**
  3157. * Normalize the current Vector3 to a new vector
  3158. * @returns the new Vector3
  3159. */
  3160. Vector3.prototype.normalizeToNew = function () {
  3161. var normalized = new Vector3(0, 0, 0);
  3162. this.normalizeToRef(normalized);
  3163. return normalized;
  3164. };
  3165. /**
  3166. * Normalize the current Vector3 to the reference
  3167. * @param reference define the Vector3 to update
  3168. * @returns the updated Vector3
  3169. */
  3170. Vector3.prototype.normalizeToRef = function (reference) {
  3171. var len = this.length();
  3172. if (len === 0 || len === 1.0) {
  3173. reference.set(this.x, this.y, this.z);
  3174. return reference;
  3175. }
  3176. var scale = 1.0 / len;
  3177. this.scaleToRef(scale, reference);
  3178. return reference;
  3179. };
  3180. /**
  3181. * Creates a new Vector3 copied from the current Vector3
  3182. * @returns the new Vector3
  3183. */
  3184. Vector3.prototype.clone = function () {
  3185. return new Vector3(this.x, this.y, this.z);
  3186. };
  3187. /**
  3188. * Copies the given vector coordinates to the current Vector3 ones
  3189. * @param source defines the source Vector3
  3190. * @returns the current updated Vector3
  3191. */
  3192. Vector3.prototype.copyFrom = function (source) {
  3193. this.x = source.x;
  3194. this.y = source.y;
  3195. this.z = source.z;
  3196. return this;
  3197. };
  3198. /**
  3199. * Copies the given floats to the current Vector3 coordinates
  3200. * @param x defines the x coordinate of the operand
  3201. * @param y defines the y coordinate of the operand
  3202. * @param z defines the z coordinate of the operand
  3203. * @returns the current updated Vector3
  3204. */
  3205. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3206. this.x = x;
  3207. this.y = y;
  3208. this.z = z;
  3209. return this;
  3210. };
  3211. /**
  3212. * Copies the given floats to the current Vector3 coordinates
  3213. * @param x defines the x coordinate of the operand
  3214. * @param y defines the y coordinate of the operand
  3215. * @param z defines the z coordinate of the operand
  3216. * @returns the current updated Vector3
  3217. */
  3218. Vector3.prototype.set = function (x, y, z) {
  3219. return this.copyFromFloats(x, y, z);
  3220. };
  3221. // Statics
  3222. /**
  3223. * Get the clip factor between two vectors
  3224. * @param vector0 defines the first operand
  3225. * @param vector1 defines the second operand
  3226. * @param axis defines the axis to use
  3227. * @param size defines the size along the axis
  3228. * @returns the clip factor
  3229. */
  3230. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3231. var d0 = Vector3.Dot(vector0, axis) - size;
  3232. var d1 = Vector3.Dot(vector1, axis) - size;
  3233. var s = d0 / (d0 - d1);
  3234. return s;
  3235. };
  3236. /**
  3237. * Get angle between two vectors
  3238. * @param vector0 angle between vector0 and vector1
  3239. * @param vector1 angle between vector0 and vector1
  3240. * @param normal direction of the normal
  3241. * @return the angle between vector0 and vector1
  3242. */
  3243. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3244. var v0 = vector0.clone().normalize();
  3245. var v1 = vector1.clone().normalize();
  3246. var dot = Vector3.Dot(v0, v1);
  3247. var n = Vector3.Cross(v0, v1);
  3248. if (Vector3.Dot(n, normal) > 0) {
  3249. return Math.acos(dot);
  3250. }
  3251. return -Math.acos(dot);
  3252. };
  3253. /**
  3254. * Returns a new Vector3 set from the index "offset" of the given array
  3255. * @param array defines the source array
  3256. * @param offset defines the offset in the source array
  3257. * @returns the new Vector3
  3258. */
  3259. Vector3.FromArray = function (array, offset) {
  3260. if (!offset) {
  3261. offset = 0;
  3262. }
  3263. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3264. };
  3265. /**
  3266. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3267. * This function is deprecated. Use FromArray instead
  3268. * @param array defines the source array
  3269. * @param offset defines the offset in the source array
  3270. * @returns the new Vector3
  3271. */
  3272. Vector3.FromFloatArray = function (array, offset) {
  3273. return Vector3.FromArray(array, offset);
  3274. };
  3275. /**
  3276. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3277. * @param array defines the source array
  3278. * @param offset defines the offset in the source array
  3279. * @param result defines the Vector3 where to store the result
  3280. */
  3281. Vector3.FromArrayToRef = function (array, offset, result) {
  3282. result.x = array[offset];
  3283. result.y = array[offset + 1];
  3284. result.z = array[offset + 2];
  3285. };
  3286. /**
  3287. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3288. * This function is deprecated. Use FromArrayToRef instead.
  3289. * @param array defines the source array
  3290. * @param offset defines the offset in the source array
  3291. * @param result defines the Vector3 where to store the result
  3292. */
  3293. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3294. return Vector3.FromArrayToRef(array, offset, result);
  3295. };
  3296. /**
  3297. * Sets the given vector "result" with the given floats.
  3298. * @param x defines the x coordinate of the source
  3299. * @param y defines the y coordinate of the source
  3300. * @param z defines the z coordinate of the source
  3301. * @param result defines the Vector3 where to store the result
  3302. */
  3303. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3304. result.x = x;
  3305. result.y = y;
  3306. result.z = z;
  3307. };
  3308. /**
  3309. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3310. * @returns a new empty Vector3
  3311. */
  3312. Vector3.Zero = function () {
  3313. return new Vector3(0.0, 0.0, 0.0);
  3314. };
  3315. /**
  3316. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3317. * @returns a new unit Vector3
  3318. */
  3319. Vector3.One = function () {
  3320. return new Vector3(1.0, 1.0, 1.0);
  3321. };
  3322. /**
  3323. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3324. * @returns a new up Vector3
  3325. */
  3326. Vector3.Up = function () {
  3327. return new Vector3(0.0, 1.0, 0.0);
  3328. };
  3329. /**
  3330. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3331. * @returns a new forward Vector3
  3332. */
  3333. Vector3.Forward = function () {
  3334. return new Vector3(0.0, 0.0, 1.0);
  3335. };
  3336. /**
  3337. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3338. * @returns a new right Vector3
  3339. */
  3340. Vector3.Right = function () {
  3341. return new Vector3(1.0, 0.0, 0.0);
  3342. };
  3343. /**
  3344. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3345. * @returns a new left Vector3
  3346. */
  3347. Vector3.Left = function () {
  3348. return new Vector3(-1.0, 0.0, 0.0);
  3349. };
  3350. /**
  3351. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3352. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3353. * @param vector defines the Vector3 to transform
  3354. * @param transformation defines the transformation matrix
  3355. * @returns the transformed Vector3
  3356. */
  3357. Vector3.TransformCoordinates = function (vector, transformation) {
  3358. var result = Vector3.Zero();
  3359. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3360. return result;
  3361. };
  3362. /**
  3363. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3364. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3365. * @param vector defines the Vector3 to transform
  3366. * @param transformation defines the transformation matrix
  3367. * @param result defines the Vector3 where to store the result
  3368. */
  3369. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3370. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3371. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3372. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3373. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3374. result.x = x / w;
  3375. result.y = y / w;
  3376. result.z = z / w;
  3377. };
  3378. /**
  3379. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3380. * This method computes tranformed coordinates only, not transformed direction vectors
  3381. * @param x define the x coordinate of the source vector
  3382. * @param y define the y coordinate of the source vector
  3383. * @param z define the z coordinate of the source vector
  3384. * @param transformation defines the transformation matrix
  3385. * @param result defines the Vector3 where to store the result
  3386. */
  3387. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3388. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3389. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3390. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3391. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3392. result.x = rx / rw;
  3393. result.y = ry / rw;
  3394. result.z = rz / rw;
  3395. };
  3396. /**
  3397. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3398. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3399. * @param vector defines the Vector3 to transform
  3400. * @param transformation defines the transformation matrix
  3401. * @returns the new Vector3
  3402. */
  3403. Vector3.TransformNormal = function (vector, transformation) {
  3404. var result = Vector3.Zero();
  3405. Vector3.TransformNormalToRef(vector, transformation, result);
  3406. return result;
  3407. };
  3408. /**
  3409. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3410. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3411. * @param vector defines the Vector3 to transform
  3412. * @param transformation defines the transformation matrix
  3413. * @param result defines the Vector3 where to store the result
  3414. */
  3415. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3416. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3417. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3418. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3419. result.x = x;
  3420. result.y = y;
  3421. result.z = z;
  3422. };
  3423. /**
  3424. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3425. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3426. * @param x define the x coordinate of the source vector
  3427. * @param y define the y coordinate of the source vector
  3428. * @param z define the z coordinate of the source vector
  3429. * @param transformation defines the transformation matrix
  3430. * @param result defines the Vector3 where to store the result
  3431. */
  3432. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3433. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3434. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3435. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3436. };
  3437. /**
  3438. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3439. * @param value1 defines the first control point
  3440. * @param value2 defines the second control point
  3441. * @param value3 defines the third control point
  3442. * @param value4 defines the fourth control point
  3443. * @param amount defines the amount on the spline to use
  3444. * @returns the new Vector3
  3445. */
  3446. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3447. var squared = amount * amount;
  3448. var cubed = amount * squared;
  3449. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3450. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3451. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3452. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3453. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3454. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3455. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3456. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3457. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3458. return new Vector3(x, y, z);
  3459. };
  3460. /**
  3461. * 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"
  3462. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3463. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3464. * @param value defines the current value
  3465. * @param min defines the lower range value
  3466. * @param max defines the upper range value
  3467. * @returns the new Vector3
  3468. */
  3469. Vector3.Clamp = function (value, min, max) {
  3470. var x = value.x;
  3471. x = (x > max.x) ? max.x : x;
  3472. x = (x < min.x) ? min.x : x;
  3473. var y = value.y;
  3474. y = (y > max.y) ? max.y : y;
  3475. y = (y < min.y) ? min.y : y;
  3476. var z = value.z;
  3477. z = (z > max.z) ? max.z : z;
  3478. z = (z < min.z) ? min.z : z;
  3479. return new Vector3(x, y, z);
  3480. };
  3481. /**
  3482. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3483. * @param value1 defines the first control point
  3484. * @param tangent1 defines the first tangent vector
  3485. * @param value2 defines the second control point
  3486. * @param tangent2 defines the second tangent vector
  3487. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3488. * @returns the new Vector3
  3489. */
  3490. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3491. var squared = amount * amount;
  3492. var cubed = amount * squared;
  3493. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3494. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3495. var part3 = (cubed - (2.0 * squared)) + amount;
  3496. var part4 = cubed - squared;
  3497. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3498. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3499. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3500. return new Vector3(x, y, z);
  3501. };
  3502. /**
  3503. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3504. * @param start defines the start value
  3505. * @param end defines the end value
  3506. * @param amount max defines amount between both (between 0 and 1)
  3507. * @returns the new Vector3
  3508. */
  3509. Vector3.Lerp = function (start, end, amount) {
  3510. var result = new Vector3(0, 0, 0);
  3511. Vector3.LerpToRef(start, end, amount, result);
  3512. return result;
  3513. };
  3514. /**
  3515. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3516. * @param start defines the start value
  3517. * @param end defines the end value
  3518. * @param amount max defines amount between both (between 0 and 1)
  3519. * @param result defines the Vector3 where to store the result
  3520. */
  3521. Vector3.LerpToRef = function (start, end, amount, result) {
  3522. result.x = start.x + ((end.x - start.x) * amount);
  3523. result.y = start.y + ((end.y - start.y) * amount);
  3524. result.z = start.z + ((end.z - start.z) * amount);
  3525. };
  3526. /**
  3527. * Returns the dot product (float) between the vectors "left" and "right"
  3528. * @param left defines the left operand
  3529. * @param right defines the right operand
  3530. * @returns the dot product
  3531. */
  3532. Vector3.Dot = function (left, right) {
  3533. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3534. };
  3535. /**
  3536. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3537. * The cross product is then orthogonal to both "left" and "right"
  3538. * @param left defines the left operand
  3539. * @param right defines the right operand
  3540. * @returns the cross product
  3541. */
  3542. Vector3.Cross = function (left, right) {
  3543. var result = Vector3.Zero();
  3544. Vector3.CrossToRef(left, right, result);
  3545. return result;
  3546. };
  3547. /**
  3548. * Sets the given vector "result" with the cross product of "left" and "right"
  3549. * The cross product is then orthogonal to both "left" and "right"
  3550. * @param left defines the left operand
  3551. * @param right defines the right operand
  3552. * @param result defines the Vector3 where to store the result
  3553. */
  3554. Vector3.CrossToRef = function (left, right, result) {
  3555. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3556. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3557. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3558. result.copyFrom(MathTmp.Vector3[0]);
  3559. };
  3560. /**
  3561. * Returns a new Vector3 as the normalization of the given vector
  3562. * @param vector defines the Vector3 to normalize
  3563. * @returns the new Vector3
  3564. */
  3565. Vector3.Normalize = function (vector) {
  3566. var result = Vector3.Zero();
  3567. Vector3.NormalizeToRef(vector, result);
  3568. return result;
  3569. };
  3570. /**
  3571. * Sets the given vector "result" with the normalization of the given first vector
  3572. * @param vector defines the Vector3 to normalize
  3573. * @param result defines the Vector3 where to store the result
  3574. */
  3575. Vector3.NormalizeToRef = function (vector, result) {
  3576. result.copyFrom(vector);
  3577. result.normalize();
  3578. };
  3579. /**
  3580. * Project a Vector3 onto screen space
  3581. * @param vector defines the Vector3 to project
  3582. * @param world defines the world matrix to use
  3583. * @param transform defines the transform (view x projection) matrix to use
  3584. * @param viewport defines the screen viewport to use
  3585. * @returns the new Vector3
  3586. */
  3587. Vector3.Project = function (vector, world, transform, viewport) {
  3588. var cw = viewport.width;
  3589. var ch = viewport.height;
  3590. var cx = viewport.x;
  3591. var cy = viewport.y;
  3592. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3593. 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);
  3594. var matrix = MathTmp.Matrix[0];
  3595. world.multiplyToRef(transform, matrix);
  3596. matrix.multiplyToRef(viewportMatrix, matrix);
  3597. return Vector3.TransformCoordinates(vector, matrix);
  3598. };
  3599. /**
  3600. * Unproject from screen space to object space
  3601. * @param source defines the screen space Vector3 to use
  3602. * @param viewportWidth defines the current width of the viewport
  3603. * @param viewportHeight defines the current height of the viewport
  3604. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3605. * @param transform defines the transform (view x projection) matrix to use
  3606. * @returns the new Vector3
  3607. */
  3608. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3609. var matrix = MathTmp.Matrix[0];
  3610. world.multiplyToRef(transform, matrix);
  3611. matrix.invert();
  3612. source.x = source.x / viewportWidth * 2 - 1;
  3613. source.y = -(source.y / viewportHeight * 2 - 1);
  3614. var vector = Vector3.TransformCoordinates(source, matrix);
  3615. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3616. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3617. vector = vector.scale(1.0 / num);
  3618. }
  3619. return vector;
  3620. };
  3621. /**
  3622. * Unproject from screen space to object space
  3623. * @param source defines the screen space Vector3 to use
  3624. * @param viewportWidth defines the current width of the viewport
  3625. * @param viewportHeight defines the current height of the viewport
  3626. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3627. * @param view defines the view matrix to use
  3628. * @param projection defines the projection matrix to use
  3629. * @returns the new Vector3
  3630. */
  3631. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3632. var result = Vector3.Zero();
  3633. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3634. return result;
  3635. };
  3636. /**
  3637. * Unproject from screen space to object space
  3638. * @param source defines the screen space Vector3 to use
  3639. * @param viewportWidth defines the current width of the viewport
  3640. * @param viewportHeight defines the current height of the viewport
  3641. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3642. * @param view defines the view matrix to use
  3643. * @param projection defines the projection matrix to use
  3644. * @param result defines the Vector3 where to store the result
  3645. */
  3646. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3647. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3648. };
  3649. /**
  3650. * Unproject from screen space to object space
  3651. * @param sourceX defines the screen space x coordinate to use
  3652. * @param sourceY defines the screen space y coordinate to use
  3653. * @param sourceZ defines the screen space z coordinate to use
  3654. * @param viewportWidth defines the current width of the viewport
  3655. * @param viewportHeight defines the current height of the viewport
  3656. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3657. * @param view defines the view matrix to use
  3658. * @param projection defines the projection matrix to use
  3659. * @param result defines the Vector3 where to store the result
  3660. */
  3661. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3662. var matrix = MathTmp.Matrix[0];
  3663. world.multiplyToRef(view, matrix);
  3664. matrix.multiplyToRef(projection, matrix);
  3665. matrix.invert();
  3666. var screenSource = MathTmp.Vector3[0];
  3667. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3668. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3669. screenSource.z = 2 * sourceZ - 1.0;
  3670. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3671. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3672. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3673. result.scaleInPlace(1.0 / num);
  3674. }
  3675. };
  3676. /**
  3677. * Gets the minimal coordinate values between two Vector3
  3678. * @param left defines the first operand
  3679. * @param right defines the second operand
  3680. * @returns the new Vector3
  3681. */
  3682. Vector3.Minimize = function (left, right) {
  3683. var min = left.clone();
  3684. min.minimizeInPlace(right);
  3685. return min;
  3686. };
  3687. /**
  3688. * Gets the maximal coordinate values between two Vector3
  3689. * @param left defines the first operand
  3690. * @param right defines the second operand
  3691. * @returns the new Vector3
  3692. */
  3693. Vector3.Maximize = function (left, right) {
  3694. var max = left.clone();
  3695. max.maximizeInPlace(right);
  3696. return max;
  3697. };
  3698. /**
  3699. * Returns the distance between the vectors "value1" and "value2"
  3700. * @param value1 defines the first operand
  3701. * @param value2 defines the second operand
  3702. * @returns the distance
  3703. */
  3704. Vector3.Distance = function (value1, value2) {
  3705. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3706. };
  3707. /**
  3708. * Returns the squared distance between the vectors "value1" and "value2"
  3709. * @param value1 defines the first operand
  3710. * @param value2 defines the second operand
  3711. * @returns the squared distance
  3712. */
  3713. Vector3.DistanceSquared = function (value1, value2) {
  3714. var x = value1.x - value2.x;
  3715. var y = value1.y - value2.y;
  3716. var z = value1.z - value2.z;
  3717. return (x * x) + (y * y) + (z * z);
  3718. };
  3719. /**
  3720. * Returns a new Vector3 located at the center between "value1" and "value2"
  3721. * @param value1 defines the first operand
  3722. * @param value2 defines the second operand
  3723. * @returns the new Vector3
  3724. */
  3725. Vector3.Center = function (value1, value2) {
  3726. var center = value1.add(value2);
  3727. center.scaleInPlace(0.5);
  3728. return center;
  3729. };
  3730. /**
  3731. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3732. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3733. * to something in order to rotate it from its local system to the given target system
  3734. * Note: axis1, axis2 and axis3 are normalized during this operation
  3735. * @param axis1 defines the first axis
  3736. * @param axis2 defines the second axis
  3737. * @param axis3 defines the third axis
  3738. * @returns a new Vector3
  3739. */
  3740. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3741. var rotation = Vector3.Zero();
  3742. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3743. return rotation;
  3744. };
  3745. /**
  3746. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3747. * @param axis1 defines the first axis
  3748. * @param axis2 defines the second axis
  3749. * @param axis3 defines the third axis
  3750. * @param ref defines the Vector3 where to store the result
  3751. */
  3752. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3753. var quat = MathTmp.Quaternion[0];
  3754. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3755. quat.toEulerAnglesToRef(ref);
  3756. };
  3757. return Vector3;
  3758. }());
  3759. BABYLON.Vector3 = Vector3;
  3760. //Vector4 class created for EulerAngle class conversion to Quaternion
  3761. var Vector4 = /** @class */ (function () {
  3762. /**
  3763. * Creates a Vector4 object from the given floats.
  3764. */
  3765. function Vector4(x, y, z, w) {
  3766. this.x = x;
  3767. this.y = y;
  3768. this.z = z;
  3769. this.w = w;
  3770. }
  3771. /**
  3772. * Returns the string with the Vector4 coordinates.
  3773. */
  3774. Vector4.prototype.toString = function () {
  3775. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3776. };
  3777. /**
  3778. * Returns the string "Vector4".
  3779. */
  3780. Vector4.prototype.getClassName = function () {
  3781. return "Vector4";
  3782. };
  3783. /**
  3784. * Returns the Vector4 hash code.
  3785. */
  3786. Vector4.prototype.getHashCode = function () {
  3787. var hash = this.x || 0;
  3788. hash = (hash * 397) ^ (this.y || 0);
  3789. hash = (hash * 397) ^ (this.z || 0);
  3790. hash = (hash * 397) ^ (this.w || 0);
  3791. return hash;
  3792. };
  3793. // Operators
  3794. /**
  3795. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3796. */
  3797. Vector4.prototype.asArray = function () {
  3798. var result = new Array();
  3799. this.toArray(result, 0);
  3800. return result;
  3801. };
  3802. /**
  3803. * Populates the given array from the given index with the Vector4 coordinates.
  3804. * Returns the Vector4.
  3805. */
  3806. Vector4.prototype.toArray = function (array, index) {
  3807. if (index === undefined) {
  3808. index = 0;
  3809. }
  3810. array[index] = this.x;
  3811. array[index + 1] = this.y;
  3812. array[index + 2] = this.z;
  3813. array[index + 3] = this.w;
  3814. return this;
  3815. };
  3816. /**
  3817. * Adds the given vector to the current Vector4.
  3818. * Returns the updated Vector4.
  3819. */
  3820. Vector4.prototype.addInPlace = function (otherVector) {
  3821. this.x += otherVector.x;
  3822. this.y += otherVector.y;
  3823. this.z += otherVector.z;
  3824. this.w += otherVector.w;
  3825. return this;
  3826. };
  3827. /**
  3828. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3829. */
  3830. Vector4.prototype.add = function (otherVector) {
  3831. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3832. };
  3833. /**
  3834. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3835. * Returns the current Vector4.
  3836. */
  3837. Vector4.prototype.addToRef = function (otherVector, result) {
  3838. result.x = this.x + otherVector.x;
  3839. result.y = this.y + otherVector.y;
  3840. result.z = this.z + otherVector.z;
  3841. result.w = this.w + otherVector.w;
  3842. return this;
  3843. };
  3844. /**
  3845. * Subtract in place the given vector from the current Vector4.
  3846. * Returns the updated Vector4.
  3847. */
  3848. Vector4.prototype.subtractInPlace = function (otherVector) {
  3849. this.x -= otherVector.x;
  3850. this.y -= otherVector.y;
  3851. this.z -= otherVector.z;
  3852. this.w -= otherVector.w;
  3853. return this;
  3854. };
  3855. /**
  3856. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3857. */
  3858. Vector4.prototype.subtract = function (otherVector) {
  3859. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3860. };
  3861. /**
  3862. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3863. * Returns the current Vector4.
  3864. */
  3865. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3866. result.x = this.x - otherVector.x;
  3867. result.y = this.y - otherVector.y;
  3868. result.z = this.z - otherVector.z;
  3869. result.w = this.w - otherVector.w;
  3870. return this;
  3871. };
  3872. /**
  3873. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3874. */
  3875. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3876. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3877. };
  3878. /**
  3879. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3880. * Returns the current Vector4.
  3881. */
  3882. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3883. result.x = this.x - x;
  3884. result.y = this.y - y;
  3885. result.z = this.z - z;
  3886. result.w = this.w - w;
  3887. return this;
  3888. };
  3889. /**
  3890. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3891. */
  3892. Vector4.prototype.negate = function () {
  3893. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3894. };
  3895. /**
  3896. * Multiplies the current Vector4 coordinates by scale (float).
  3897. * Returns the updated Vector4.
  3898. */
  3899. Vector4.prototype.scaleInPlace = function (scale) {
  3900. this.x *= scale;
  3901. this.y *= scale;
  3902. this.z *= scale;
  3903. this.w *= scale;
  3904. return this;
  3905. };
  3906. /**
  3907. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3908. */
  3909. Vector4.prototype.scale = function (scale) {
  3910. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3911. };
  3912. /**
  3913. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3914. * Returns the current Vector4.
  3915. */
  3916. Vector4.prototype.scaleToRef = function (scale, result) {
  3917. result.x = this.x * scale;
  3918. result.y = this.y * scale;
  3919. result.z = this.z * scale;
  3920. result.w = this.w * scale;
  3921. return this;
  3922. };
  3923. /**
  3924. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3925. * @param scale defines the scale factor
  3926. * @param result defines the Vector4 object where to store the result
  3927. * @returns the unmodified current Vector4
  3928. */
  3929. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3930. result.x += this.x * scale;
  3931. result.y += this.y * scale;
  3932. result.z += this.z * scale;
  3933. result.w += this.w * scale;
  3934. return this;
  3935. };
  3936. /**
  3937. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3938. */
  3939. Vector4.prototype.equals = function (otherVector) {
  3940. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3941. };
  3942. /**
  3943. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3944. */
  3945. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3946. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3947. return otherVector
  3948. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3949. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3950. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3951. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3952. };
  3953. /**
  3954. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3955. */
  3956. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3957. return this.x === x && this.y === y && this.z === z && this.w === w;
  3958. };
  3959. /**
  3960. * Multiplies in place the current Vector4 by the given one.
  3961. * Returns the updated Vector4.
  3962. */
  3963. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3964. this.x *= otherVector.x;
  3965. this.y *= otherVector.y;
  3966. this.z *= otherVector.z;
  3967. this.w *= otherVector.w;
  3968. return this;
  3969. };
  3970. /**
  3971. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3972. */
  3973. Vector4.prototype.multiply = function (otherVector) {
  3974. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3975. };
  3976. /**
  3977. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3978. * Returns the current Vector4.
  3979. */
  3980. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3981. result.x = this.x * otherVector.x;
  3982. result.y = this.y * otherVector.y;
  3983. result.z = this.z * otherVector.z;
  3984. result.w = this.w * otherVector.w;
  3985. return this;
  3986. };
  3987. /**
  3988. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3989. */
  3990. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3991. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3992. };
  3993. /**
  3994. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3995. */
  3996. Vector4.prototype.divide = function (otherVector) {
  3997. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3998. };
  3999. /**
  4000. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4001. * Returns the current Vector4.
  4002. */
  4003. Vector4.prototype.divideToRef = function (otherVector, result) {
  4004. result.x = this.x / otherVector.x;
  4005. result.y = this.y / otherVector.y;
  4006. result.z = this.z / otherVector.z;
  4007. result.w = this.w / otherVector.w;
  4008. return this;
  4009. };
  4010. /**
  4011. * Divides the current Vector3 coordinates by the given ones.
  4012. * @returns the updated Vector3.
  4013. */
  4014. Vector4.prototype.divideInPlace = function (otherVector) {
  4015. return this.divideToRef(otherVector, this);
  4016. };
  4017. /**
  4018. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4019. * @param other defines the second operand
  4020. * @returns the current updated Vector4
  4021. */
  4022. Vector4.prototype.minimizeInPlace = function (other) {
  4023. if (other.x < this.x)
  4024. this.x = other.x;
  4025. if (other.y < this.y)
  4026. this.y = other.y;
  4027. if (other.z < this.z)
  4028. this.z = other.z;
  4029. if (other.w < this.w)
  4030. this.w = other.w;
  4031. return this;
  4032. };
  4033. /**
  4034. * Updates the Vector4 coordinates with the maximum 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.maximizeInPlace = 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. // Properties
  4050. /**
  4051. * Returns the Vector4 length (float).
  4052. */
  4053. Vector4.prototype.length = function () {
  4054. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4055. };
  4056. /**
  4057. * Returns the Vector4 squared length (float).
  4058. */
  4059. Vector4.prototype.lengthSquared = function () {
  4060. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4061. };
  4062. // Methods
  4063. /**
  4064. * Normalizes in place the Vector4.
  4065. * Returns the updated Vector4.
  4066. */
  4067. Vector4.prototype.normalize = function () {
  4068. var len = this.length();
  4069. if (len === 0)
  4070. return this;
  4071. var num = 1.0 / len;
  4072. this.x *= num;
  4073. this.y *= num;
  4074. this.z *= num;
  4075. this.w *= num;
  4076. return this;
  4077. };
  4078. /**
  4079. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4080. */
  4081. Vector4.prototype.toVector3 = function () {
  4082. return new Vector3(this.x, this.y, this.z);
  4083. };
  4084. /**
  4085. * Returns a new Vector4 copied from the current one.
  4086. */
  4087. Vector4.prototype.clone = function () {
  4088. return new Vector4(this.x, this.y, this.z, this.w);
  4089. };
  4090. /**
  4091. * Updates the current Vector4 with the given one coordinates.
  4092. * Returns the updated Vector4.
  4093. */
  4094. Vector4.prototype.copyFrom = function (source) {
  4095. this.x = source.x;
  4096. this.y = source.y;
  4097. this.z = source.z;
  4098. this.w = source.w;
  4099. return this;
  4100. };
  4101. /**
  4102. * Updates the current Vector4 coordinates with the given floats.
  4103. * Returns the updated Vector4.
  4104. */
  4105. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4106. this.x = x;
  4107. this.y = y;
  4108. this.z = z;
  4109. this.w = w;
  4110. return this;
  4111. };
  4112. /**
  4113. * Updates the current Vector4 coordinates with the given floats.
  4114. * Returns the updated Vector4.
  4115. */
  4116. Vector4.prototype.set = function (x, y, z, w) {
  4117. return this.copyFromFloats(x, y, z, w);
  4118. };
  4119. // Statics
  4120. /**
  4121. * Returns a new Vector4 set from the starting index of the given array.
  4122. */
  4123. Vector4.FromArray = function (array, offset) {
  4124. if (!offset) {
  4125. offset = 0;
  4126. }
  4127. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4128. };
  4129. /**
  4130. * Updates the given vector "result" from the starting index of the given array.
  4131. */
  4132. Vector4.FromArrayToRef = function (array, offset, result) {
  4133. result.x = array[offset];
  4134. result.y = array[offset + 1];
  4135. result.z = array[offset + 2];
  4136. result.w = array[offset + 3];
  4137. };
  4138. /**
  4139. * Updates the given vector "result" from the starting index of the given Float32Array.
  4140. */
  4141. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4142. Vector4.FromArrayToRef(array, offset, result);
  4143. };
  4144. /**
  4145. * Updates the given vector "result" coordinates from the given floats.
  4146. */
  4147. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4148. result.x = x;
  4149. result.y = y;
  4150. result.z = z;
  4151. result.w = w;
  4152. };
  4153. /**
  4154. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4155. */
  4156. Vector4.Zero = function () {
  4157. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4158. };
  4159. /**
  4160. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4161. */
  4162. Vector4.One = function () {
  4163. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4164. };
  4165. /**
  4166. * Returns a new normalized Vector4 from the given one.
  4167. */
  4168. Vector4.Normalize = function (vector) {
  4169. var result = Vector4.Zero();
  4170. Vector4.NormalizeToRef(vector, result);
  4171. return result;
  4172. };
  4173. /**
  4174. * Updates the given vector "result" from the normalization of the given one.
  4175. */
  4176. Vector4.NormalizeToRef = function (vector, result) {
  4177. result.copyFrom(vector);
  4178. result.normalize();
  4179. };
  4180. Vector4.Minimize = function (left, right) {
  4181. var min = left.clone();
  4182. min.minimizeInPlace(right);
  4183. return min;
  4184. };
  4185. Vector4.Maximize = function (left, right) {
  4186. var max = left.clone();
  4187. max.maximizeInPlace(right);
  4188. return max;
  4189. };
  4190. /**
  4191. * Returns the distance (float) between the vectors "value1" and "value2".
  4192. */
  4193. Vector4.Distance = function (value1, value2) {
  4194. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4195. };
  4196. /**
  4197. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4198. */
  4199. Vector4.DistanceSquared = function (value1, value2) {
  4200. var x = value1.x - value2.x;
  4201. var y = value1.y - value2.y;
  4202. var z = value1.z - value2.z;
  4203. var w = value1.w - value2.w;
  4204. return (x * x) + (y * y) + (z * z) + (w * w);
  4205. };
  4206. /**
  4207. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4208. */
  4209. Vector4.Center = function (value1, value2) {
  4210. var center = value1.add(value2);
  4211. center.scaleInPlace(0.5);
  4212. return center;
  4213. };
  4214. /**
  4215. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4216. * This methods computes transformed normalized direction vectors only.
  4217. */
  4218. Vector4.TransformNormal = function (vector, transformation) {
  4219. var result = Vector4.Zero();
  4220. Vector4.TransformNormalToRef(vector, transformation, result);
  4221. return result;
  4222. };
  4223. /**
  4224. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4225. * This methods computes transformed normalized direction vectors only.
  4226. */
  4227. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4228. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4229. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4230. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4231. result.x = x;
  4232. result.y = y;
  4233. result.z = z;
  4234. result.w = vector.w;
  4235. };
  4236. /**
  4237. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4238. * This methods computes transformed normalized direction vectors only.
  4239. */
  4240. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4241. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4242. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4243. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4244. result.w = w;
  4245. };
  4246. return Vector4;
  4247. }());
  4248. BABYLON.Vector4 = Vector4;
  4249. var Size = /** @class */ (function () {
  4250. /**
  4251. * Creates a Size object from the given width and height (floats).
  4252. */
  4253. function Size(width, height) {
  4254. this.width = width;
  4255. this.height = height;
  4256. }
  4257. // Returns a string with the Size width and height.
  4258. Size.prototype.toString = function () {
  4259. return "{W: " + this.width + ", H: " + this.height + "}";
  4260. };
  4261. /**
  4262. * Returns the string "Size"
  4263. */
  4264. Size.prototype.getClassName = function () {
  4265. return "Size";
  4266. };
  4267. /**
  4268. * Returns the Size hash code.
  4269. */
  4270. Size.prototype.getHashCode = function () {
  4271. var hash = this.width || 0;
  4272. hash = (hash * 397) ^ (this.height || 0);
  4273. return hash;
  4274. };
  4275. /**
  4276. * Updates the current size from the given one.
  4277. * Returns the updated Size.
  4278. */
  4279. Size.prototype.copyFrom = function (src) {
  4280. this.width = src.width;
  4281. this.height = src.height;
  4282. };
  4283. /**
  4284. * Updates in place the current Size from the given floats.
  4285. * Returns the updated Size.
  4286. */
  4287. Size.prototype.copyFromFloats = function (width, height) {
  4288. this.width = width;
  4289. this.height = height;
  4290. return this;
  4291. };
  4292. /**
  4293. * Updates in place the current Size from the given floats.
  4294. * Returns the updated Size.
  4295. */
  4296. Size.prototype.set = function (width, height) {
  4297. return this.copyFromFloats(width, height);
  4298. };
  4299. /**
  4300. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4301. */
  4302. Size.prototype.multiplyByFloats = function (w, h) {
  4303. return new Size(this.width * w, this.height * h);
  4304. };
  4305. /**
  4306. * Returns a new Size copied from the given one.
  4307. */
  4308. Size.prototype.clone = function () {
  4309. return new Size(this.width, this.height);
  4310. };
  4311. /**
  4312. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4313. */
  4314. Size.prototype.equals = function (other) {
  4315. if (!other) {
  4316. return false;
  4317. }
  4318. return (this.width === other.width) && (this.height === other.height);
  4319. };
  4320. Object.defineProperty(Size.prototype, "surface", {
  4321. /**
  4322. * Returns the surface of the Size : width * height (float).
  4323. */
  4324. get: function () {
  4325. return this.width * this.height;
  4326. },
  4327. enumerable: true,
  4328. configurable: true
  4329. });
  4330. /**
  4331. * Returns a new Size set to (0.0, 0.0)
  4332. */
  4333. Size.Zero = function () {
  4334. return new Size(0.0, 0.0);
  4335. };
  4336. /**
  4337. * Returns a new Size set as the addition result of the current Size and the given one.
  4338. */
  4339. Size.prototype.add = function (otherSize) {
  4340. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4341. return r;
  4342. };
  4343. /**
  4344. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4345. */
  4346. Size.prototype.subtract = function (otherSize) {
  4347. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4348. return r;
  4349. };
  4350. /**
  4351. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4352. */
  4353. Size.Lerp = function (start, end, amount) {
  4354. var w = start.width + ((end.width - start.width) * amount);
  4355. var h = start.height + ((end.height - start.height) * amount);
  4356. return new Size(w, h);
  4357. };
  4358. return Size;
  4359. }());
  4360. BABYLON.Size = Size;
  4361. /**
  4362. * Class used to store quaternion data
  4363. * @see https://en.wikipedia.org/wiki/Quaternion
  4364. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4365. */
  4366. var Quaternion = /** @class */ (function () {
  4367. /**
  4368. * Creates a new Quaternion from the given floats
  4369. * @param x defines the first component (0 by default)
  4370. * @param y defines the second component (0 by default)
  4371. * @param z defines the third component (0 by default)
  4372. * @param w defines the fourth component (1.0 by default)
  4373. */
  4374. function Quaternion(
  4375. /** defines the first component (0 by default) */
  4376. x,
  4377. /** defines the second component (0 by default) */
  4378. y,
  4379. /** defines the third component (0 by default) */
  4380. z,
  4381. /** defines the fourth component (1.0 by default) */
  4382. w) {
  4383. if (x === void 0) { x = 0.0; }
  4384. if (y === void 0) { y = 0.0; }
  4385. if (z === void 0) { z = 0.0; }
  4386. if (w === void 0) { w = 1.0; }
  4387. this.x = x;
  4388. this.y = y;
  4389. this.z = z;
  4390. this.w = w;
  4391. }
  4392. /**
  4393. * Gets a string representation for the current quaternion
  4394. * @returns a string with the Quaternion coordinates
  4395. */
  4396. Quaternion.prototype.toString = function () {
  4397. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4398. };
  4399. /**
  4400. * Gets the class name of the quaternion
  4401. * @returns the string "Quaternion"
  4402. */
  4403. Quaternion.prototype.getClassName = function () {
  4404. return "Quaternion";
  4405. };
  4406. /**
  4407. * Gets a hash code for this quaternion
  4408. * @returns the quaternion hash code
  4409. */
  4410. Quaternion.prototype.getHashCode = function () {
  4411. var hash = this.x || 0;
  4412. hash = (hash * 397) ^ (this.y || 0);
  4413. hash = (hash * 397) ^ (this.z || 0);
  4414. hash = (hash * 397) ^ (this.w || 0);
  4415. return hash;
  4416. };
  4417. /**
  4418. * Copy the quaternion to an array
  4419. * @returns a new array populated with 4 elements from the quaternion coordinates
  4420. */
  4421. Quaternion.prototype.asArray = function () {
  4422. return [this.x, this.y, this.z, this.w];
  4423. };
  4424. /**
  4425. * Check if two quaternions are equals
  4426. * @param otherQuaternion defines the second operand
  4427. * @return true if the current quaternion and the given one coordinates are strictly equals
  4428. */
  4429. Quaternion.prototype.equals = function (otherQuaternion) {
  4430. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4431. };
  4432. /**
  4433. * Clone the current quaternion
  4434. * @returns a new quaternion copied from the current one
  4435. */
  4436. Quaternion.prototype.clone = function () {
  4437. return new Quaternion(this.x, this.y, this.z, this.w);
  4438. };
  4439. /**
  4440. * Copy a quaternion to the current one
  4441. * @param other defines the other quaternion
  4442. * @returns the updated current quaternion
  4443. */
  4444. Quaternion.prototype.copyFrom = function (other) {
  4445. this.x = other.x;
  4446. this.y = other.y;
  4447. this.z = other.z;
  4448. this.w = other.w;
  4449. return this;
  4450. };
  4451. /**
  4452. * Updates the current quaternion with the given float coordinates
  4453. * @param x defines the x coordinate
  4454. * @param y defines the y coordinate
  4455. * @param z defines the z coordinate
  4456. * @param w defines the w coordinate
  4457. * @returns the updated current quaternion
  4458. */
  4459. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4460. this.x = x;
  4461. this.y = y;
  4462. this.z = z;
  4463. this.w = w;
  4464. return this;
  4465. };
  4466. /**
  4467. * Updates the current quaternion from the given float coordinates
  4468. * @param x defines the x coordinate
  4469. * @param y defines the y coordinate
  4470. * @param z defines the z coordinate
  4471. * @param w defines the w coordinate
  4472. * @returns the updated current quaternion
  4473. */
  4474. Quaternion.prototype.set = function (x, y, z, w) {
  4475. return this.copyFromFloats(x, y, z, w);
  4476. };
  4477. /**
  4478. * Adds two quaternions
  4479. * @param other defines the second operand
  4480. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4481. */
  4482. Quaternion.prototype.add = function (other) {
  4483. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4484. };
  4485. /**
  4486. * Add a quaternion to the current one
  4487. * @param other defines the quaternion to add
  4488. * @returns the current quaternion
  4489. */
  4490. Quaternion.prototype.addInPlace = function (other) {
  4491. this.x += other.x;
  4492. this.y += other.y;
  4493. this.z += other.z;
  4494. this.w += other.w;
  4495. return this;
  4496. };
  4497. /**
  4498. * Subtract two quaternions
  4499. * @param other defines the second operand
  4500. * @returns a new quaternion as the subtraction result of the given one from the current one
  4501. */
  4502. Quaternion.prototype.subtract = function (other) {
  4503. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4504. };
  4505. /**
  4506. * Multiplies the current quaternion by a scale factor
  4507. * @param value defines the scale factor
  4508. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4509. */
  4510. Quaternion.prototype.scale = function (value) {
  4511. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4512. };
  4513. /**
  4514. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4515. * @param scale defines the scale factor
  4516. * @param result defines the Quaternion object where to store the result
  4517. * @returns the unmodified current quaternion
  4518. */
  4519. Quaternion.prototype.scaleToRef = function (scale, result) {
  4520. result.x = this.x * scale;
  4521. result.y = this.y * scale;
  4522. result.z = this.z * scale;
  4523. result.w = this.w * scale;
  4524. return this;
  4525. };
  4526. /**
  4527. * Multiplies in place the current quaternion by a scale factor
  4528. * @param value defines the scale factor
  4529. * @returns the current modified quaternion
  4530. */
  4531. Quaternion.prototype.scaleInPlace = function (value) {
  4532. this.x *= value;
  4533. this.y *= value;
  4534. this.z *= value;
  4535. this.w *= value;
  4536. return this;
  4537. };
  4538. /**
  4539. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4540. * @param scale defines the scale factor
  4541. * @param result defines the Quaternion object where to store the result
  4542. * @returns the unmodified current quaternion
  4543. */
  4544. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4545. result.x += this.x * scale;
  4546. result.y += this.y * scale;
  4547. result.z += this.z * scale;
  4548. result.w += this.w * scale;
  4549. return this;
  4550. };
  4551. /**
  4552. * Multiplies two quaternions
  4553. * @param q1 defines the second operand
  4554. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4555. */
  4556. Quaternion.prototype.multiply = function (q1) {
  4557. var result = new Quaternion(0, 0, 0, 1.0);
  4558. this.multiplyToRef(q1, result);
  4559. return result;
  4560. };
  4561. /**
  4562. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4563. * @param q1 defines the second operand
  4564. * @param result defines the target quaternion
  4565. * @returns the current quaternion
  4566. */
  4567. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4568. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4569. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4570. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4571. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4572. result.copyFromFloats(x, y, z, w);
  4573. return this;
  4574. };
  4575. /**
  4576. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4577. * @param q1 defines the second operand
  4578. * @returns the currentupdated quaternion
  4579. */
  4580. Quaternion.prototype.multiplyInPlace = function (q1) {
  4581. this.multiplyToRef(q1, this);
  4582. return this;
  4583. };
  4584. /**
  4585. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4586. * @param ref defines the target quaternion
  4587. * @returns the current quaternion
  4588. */
  4589. Quaternion.prototype.conjugateToRef = function (ref) {
  4590. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4591. return this;
  4592. };
  4593. /**
  4594. * Conjugates in place (1-q) the current quaternion
  4595. * @returns the current updated quaternion
  4596. */
  4597. Quaternion.prototype.conjugateInPlace = function () {
  4598. this.x *= -1;
  4599. this.y *= -1;
  4600. this.z *= -1;
  4601. return this;
  4602. };
  4603. /**
  4604. * Conjugates in place (1-q) the current quaternion
  4605. * @returns a new quaternion
  4606. */
  4607. Quaternion.prototype.conjugate = function () {
  4608. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4609. return result;
  4610. };
  4611. /**
  4612. * Gets length of current quaternion
  4613. * @returns the quaternion length (float)
  4614. */
  4615. Quaternion.prototype.length = function () {
  4616. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4617. };
  4618. /**
  4619. * Normalize in place the current quaternion
  4620. * @returns the current updated quaternion
  4621. */
  4622. Quaternion.prototype.normalize = function () {
  4623. var length = 1.0 / this.length();
  4624. this.x *= length;
  4625. this.y *= length;
  4626. this.z *= length;
  4627. this.w *= length;
  4628. return this;
  4629. };
  4630. /**
  4631. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4632. * @param order is a reserved parameter and is ignore for now
  4633. * @returns a new Vector3 containing the Euler angles
  4634. */
  4635. Quaternion.prototype.toEulerAngles = function (order) {
  4636. if (order === void 0) { order = "YZX"; }
  4637. var result = Vector3.Zero();
  4638. this.toEulerAnglesToRef(result, order);
  4639. return result;
  4640. };
  4641. /**
  4642. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4643. * @param result defines the vector which will be filled with the Euler angles
  4644. * @param order is a reserved parameter and is ignore for now
  4645. * @returns the current unchanged quaternion
  4646. */
  4647. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4648. if (order === void 0) { order = "YZX"; }
  4649. var qz = this.z;
  4650. var qx = this.x;
  4651. var qy = this.y;
  4652. var qw = this.w;
  4653. var sqw = qw * qw;
  4654. var sqz = qz * qz;
  4655. var sqx = qx * qx;
  4656. var sqy = qy * qy;
  4657. var zAxisY = qy * qz - qx * qw;
  4658. var limit = .4999999;
  4659. if (zAxisY < -limit) {
  4660. result.y = 2 * Math.atan2(qy, qw);
  4661. result.x = Math.PI / 2;
  4662. result.z = 0;
  4663. }
  4664. else if (zAxisY > limit) {
  4665. result.y = 2 * Math.atan2(qy, qw);
  4666. result.x = -Math.PI / 2;
  4667. result.z = 0;
  4668. }
  4669. else {
  4670. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4671. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4672. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4673. }
  4674. return this;
  4675. };
  4676. /**
  4677. * Updates the given rotation matrix with the current quaternion values
  4678. * @param result defines the target matrix
  4679. * @returns the current unchanged quaternion
  4680. */
  4681. Quaternion.prototype.toRotationMatrix = function (result) {
  4682. var xx = this.x * this.x;
  4683. var yy = this.y * this.y;
  4684. var zz = this.z * this.z;
  4685. var xy = this.x * this.y;
  4686. var zw = this.z * this.w;
  4687. var zx = this.z * this.x;
  4688. var yw = this.y * this.w;
  4689. var yz = this.y * this.z;
  4690. var xw = this.x * this.w;
  4691. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4692. result.m[1] = 2.0 * (xy + zw);
  4693. result.m[2] = 2.0 * (zx - yw);
  4694. result.m[3] = 0;
  4695. result.m[4] = 2.0 * (xy - zw);
  4696. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4697. result.m[6] = 2.0 * (yz + xw);
  4698. result.m[7] = 0;
  4699. result.m[8] = 2.0 * (zx + yw);
  4700. result.m[9] = 2.0 * (yz - xw);
  4701. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4702. result.m[11] = 0;
  4703. result.m[12] = 0;
  4704. result.m[13] = 0;
  4705. result.m[14] = 0;
  4706. result.m[15] = 1.0;
  4707. result._markAsUpdated();
  4708. return this;
  4709. };
  4710. /**
  4711. * Updates the current quaternion from the given rotation matrix values
  4712. * @param matrix defines the source matrix
  4713. * @returns the current updated quaternion
  4714. */
  4715. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4716. Quaternion.FromRotationMatrixToRef(matrix, this);
  4717. return this;
  4718. };
  4719. // Statics
  4720. /**
  4721. * Creates a new quaternion from a rotation matrix
  4722. * @param matrix defines the source matrix
  4723. * @returns a new quaternion created from the given rotation matrix values
  4724. */
  4725. Quaternion.FromRotationMatrix = function (matrix) {
  4726. var result = new Quaternion();
  4727. Quaternion.FromRotationMatrixToRef(matrix, result);
  4728. return result;
  4729. };
  4730. /**
  4731. * Updates the given quaternion with the given rotation matrix values
  4732. * @param matrix defines the source matrix
  4733. * @param result defines the target quaternion
  4734. */
  4735. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4736. var data = matrix.m;
  4737. var m11 = data[0], m12 = data[4], m13 = data[8];
  4738. var m21 = data[1], m22 = data[5], m23 = data[9];
  4739. var m31 = data[2], m32 = data[6], m33 = data[10];
  4740. var trace = m11 + m22 + m33;
  4741. var s;
  4742. if (trace > 0) {
  4743. s = 0.5 / Math.sqrt(trace + 1.0);
  4744. result.w = 0.25 / s;
  4745. result.x = (m32 - m23) * s;
  4746. result.y = (m13 - m31) * s;
  4747. result.z = (m21 - m12) * s;
  4748. }
  4749. else if (m11 > m22 && m11 > m33) {
  4750. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4751. result.w = (m32 - m23) / s;
  4752. result.x = 0.25 * s;
  4753. result.y = (m12 + m21) / s;
  4754. result.z = (m13 + m31) / s;
  4755. }
  4756. else if (m22 > m33) {
  4757. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4758. result.w = (m13 - m31) / s;
  4759. result.x = (m12 + m21) / s;
  4760. result.y = 0.25 * s;
  4761. result.z = (m23 + m32) / s;
  4762. }
  4763. else {
  4764. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4765. result.w = (m21 - m12) / s;
  4766. result.x = (m13 + m31) / s;
  4767. result.y = (m23 + m32) / s;
  4768. result.z = 0.25 * s;
  4769. }
  4770. };
  4771. /**
  4772. * Returns the dot product (float) between the quaternions "left" and "right"
  4773. * @param left defines the left operand
  4774. * @param right defines the right operand
  4775. * @returns the dot product
  4776. */
  4777. Quaternion.Dot = function (left, right) {
  4778. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4779. };
  4780. /**
  4781. * Checks if the two quaternions are close to each other
  4782. * @param quat0 defines the first quaternion to check
  4783. * @param quat1 defines the second quaternion to check
  4784. * @returns true if the two quaternions are close to each other
  4785. */
  4786. Quaternion.AreClose = function (quat0, quat1) {
  4787. var dot = Quaternion.Dot(quat0, quat1);
  4788. return dot >= 0;
  4789. };
  4790. /**
  4791. * Creates an empty quaternion
  4792. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4793. */
  4794. Quaternion.Zero = function () {
  4795. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4796. };
  4797. /**
  4798. * Inverse a given quaternion
  4799. * @param q defines the source quaternion
  4800. * @returns a new quaternion as the inverted current quaternion
  4801. */
  4802. Quaternion.Inverse = function (q) {
  4803. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4804. };
  4805. /**
  4806. * Creates an identity quaternion
  4807. * @returns the identity quaternion
  4808. */
  4809. Quaternion.Identity = function () {
  4810. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4811. };
  4812. /**
  4813. * Gets a boolean indicating if the given quaternion is identity
  4814. * @param quaternion defines the quaternion to check
  4815. * @returns true if the quaternion is identity
  4816. */
  4817. Quaternion.IsIdentity = function (quaternion) {
  4818. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4819. };
  4820. /**
  4821. * Creates a quaternion from a rotation around an axis
  4822. * @param axis defines the axis to use
  4823. * @param angle defines the angle to use
  4824. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4825. */
  4826. Quaternion.RotationAxis = function (axis, angle) {
  4827. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4828. };
  4829. /**
  4830. * Creates a rotation around an axis and stores it into the given quaternion
  4831. * @param axis defines the axis to use
  4832. * @param angle defines the angle to use
  4833. * @param result defines the target quaternion
  4834. * @returns the target quaternion
  4835. */
  4836. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4837. var sin = Math.sin(angle / 2);
  4838. axis.normalize();
  4839. result.w = Math.cos(angle / 2);
  4840. result.x = axis.x * sin;
  4841. result.y = axis.y * sin;
  4842. result.z = axis.z * sin;
  4843. return result;
  4844. };
  4845. /**
  4846. * Creates a new quaternion from data stored into an array
  4847. * @param array defines the data source
  4848. * @param offset defines the offset in the source array where the data starts
  4849. * @returns a new quaternion
  4850. */
  4851. Quaternion.FromArray = function (array, offset) {
  4852. if (!offset) {
  4853. offset = 0;
  4854. }
  4855. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4856. };
  4857. /**
  4858. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4859. * @param yaw defines the rotation around Y axis
  4860. * @param pitch defines the rotation around X axis
  4861. * @param roll defines the rotation around Z axis
  4862. * @returns the new quaternion
  4863. */
  4864. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4865. var q = new Quaternion();
  4866. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4867. return q;
  4868. };
  4869. /**
  4870. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4871. * @param yaw defines the rotation around Y axis
  4872. * @param pitch defines the rotation around X axis
  4873. * @param roll defines the rotation around Z axis
  4874. * @param result defines the target quaternion
  4875. */
  4876. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4877. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4878. var halfRoll = roll * 0.5;
  4879. var halfPitch = pitch * 0.5;
  4880. var halfYaw = yaw * 0.5;
  4881. var sinRoll = Math.sin(halfRoll);
  4882. var cosRoll = Math.cos(halfRoll);
  4883. var sinPitch = Math.sin(halfPitch);
  4884. var cosPitch = Math.cos(halfPitch);
  4885. var sinYaw = Math.sin(halfYaw);
  4886. var cosYaw = Math.cos(halfYaw);
  4887. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4888. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4889. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4890. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4891. };
  4892. /**
  4893. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4894. * @param alpha defines the rotation around first axis
  4895. * @param beta defines the rotation around second axis
  4896. * @param gamma defines the rotation around third axis
  4897. * @returns the new quaternion
  4898. */
  4899. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4900. var result = new Quaternion();
  4901. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4902. return result;
  4903. };
  4904. /**
  4905. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4906. * @param alpha defines the rotation around first axis
  4907. * @param beta defines the rotation around second axis
  4908. * @param gamma defines the rotation around third axis
  4909. * @param result defines the target quaternion
  4910. */
  4911. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4912. // Produces a quaternion from Euler angles in the z-x-z orientation
  4913. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4914. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4915. var halfBeta = beta * 0.5;
  4916. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4917. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4918. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4919. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4920. };
  4921. /**
  4922. * 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)
  4923. * @param axis1 defines the first axis
  4924. * @param axis2 defines the second axis
  4925. * @param axis3 defines the third axis
  4926. * @returns the new quaternion
  4927. */
  4928. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4929. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4930. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4931. return quat;
  4932. };
  4933. /**
  4934. * 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
  4935. * @param axis1 defines the first axis
  4936. * @param axis2 defines the second axis
  4937. * @param axis3 defines the third axis
  4938. * @param ref defines the target quaternion
  4939. */
  4940. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4941. var rotMat = MathTmp.Matrix[0];
  4942. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4943. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4944. };
  4945. /**
  4946. * Interpolates between two quaternions
  4947. * @param left defines first quaternion
  4948. * @param right defines second quaternion
  4949. * @param amount defines the gradient to use
  4950. * @returns the new interpolated quaternion
  4951. */
  4952. Quaternion.Slerp = function (left, right, amount) {
  4953. var result = Quaternion.Identity();
  4954. Quaternion.SlerpToRef(left, right, amount, result);
  4955. return result;
  4956. };
  4957. /**
  4958. * Interpolates between two quaternions and stores it into a target quaternion
  4959. * @param left defines first quaternion
  4960. * @param right defines second quaternion
  4961. * @param amount defines the gradient to use
  4962. * @param result defines the target quaternion
  4963. */
  4964. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4965. var num2;
  4966. var num3;
  4967. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4968. var flag = false;
  4969. if (num4 < 0) {
  4970. flag = true;
  4971. num4 = -num4;
  4972. }
  4973. if (num4 > 0.999999) {
  4974. num3 = 1 - amount;
  4975. num2 = flag ? -amount : amount;
  4976. }
  4977. else {
  4978. var num5 = Math.acos(num4);
  4979. var num6 = (1.0 / Math.sin(num5));
  4980. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4981. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4982. }
  4983. result.x = (num3 * left.x) + (num2 * right.x);
  4984. result.y = (num3 * left.y) + (num2 * right.y);
  4985. result.z = (num3 * left.z) + (num2 * right.z);
  4986. result.w = (num3 * left.w) + (num2 * right.w);
  4987. };
  4988. /**
  4989. * Interpolate between two quaternions using Hermite interpolation
  4990. * @param value1 defines first quaternion
  4991. * @param tangent1 defines the incoming tangent
  4992. * @param value2 defines second quaternion
  4993. * @param tangent2 defines the outgoing tangent
  4994. * @param amount defines the target quaternion
  4995. * @returns the new interpolated quaternion
  4996. */
  4997. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4998. var squared = amount * amount;
  4999. var cubed = amount * squared;
  5000. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5001. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5002. var part3 = (cubed - (2.0 * squared)) + amount;
  5003. var part4 = cubed - squared;
  5004. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5005. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5006. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5007. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5008. return new Quaternion(x, y, z, w);
  5009. };
  5010. return Quaternion;
  5011. }());
  5012. BABYLON.Quaternion = Quaternion;
  5013. /**
  5014. * Class used to store matrix data (4x4)
  5015. */
  5016. var Matrix = /** @class */ (function () {
  5017. /**
  5018. * Creates an empty matrix (filled with zeros)
  5019. */
  5020. function Matrix() {
  5021. this._isIdentity = false;
  5022. this._isIdentityDirty = true;
  5023. /**
  5024. * Gets or sets the internal data of the matrix
  5025. */
  5026. this.m = new Float32Array(16);
  5027. this._markAsUpdated();
  5028. }
  5029. /** @hidden */
  5030. Matrix.prototype._markAsUpdated = function () {
  5031. this.updateFlag = Matrix._updateFlagSeed++;
  5032. this._isIdentityDirty = true;
  5033. };
  5034. // Properties
  5035. /**
  5036. * Check if the current matrix is indentity
  5037. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5038. * @returns true is the matrix is the identity matrix
  5039. */
  5040. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5041. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5042. if (this._isIdentityDirty) {
  5043. this._isIdentityDirty = false;
  5044. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5045. this._isIdentity = false;
  5046. }
  5047. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5048. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5049. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5050. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5051. this._isIdentity = false;
  5052. }
  5053. else {
  5054. this._isIdentity = true;
  5055. }
  5056. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5057. this._isIdentity = false;
  5058. }
  5059. }
  5060. return this._isIdentity;
  5061. };
  5062. /**
  5063. * Gets the determinant of the matrix
  5064. * @returns the matrix determinant
  5065. */
  5066. Matrix.prototype.determinant = function () {
  5067. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5068. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5069. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5070. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5071. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5072. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5073. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5074. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5075. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5076. };
  5077. // Methods
  5078. /**
  5079. * Returns the matrix as a Float32Array
  5080. * @returns the matrix underlying array
  5081. */
  5082. Matrix.prototype.toArray = function () {
  5083. return this.m;
  5084. };
  5085. /**
  5086. * Returns the matrix as a Float32Array
  5087. * @returns the matrix underlying array.
  5088. */
  5089. Matrix.prototype.asArray = function () {
  5090. return this.toArray();
  5091. };
  5092. /**
  5093. * Inverts the current matrix in place
  5094. * @returns the current inverted matrix
  5095. */
  5096. Matrix.prototype.invert = function () {
  5097. this.invertToRef(this);
  5098. return this;
  5099. };
  5100. /**
  5101. * Sets all the matrix elements to zero
  5102. * @returns the current matrix
  5103. */
  5104. Matrix.prototype.reset = function () {
  5105. for (var index = 0; index < 16; index++) {
  5106. this.m[index] = 0.0;
  5107. }
  5108. this._markAsUpdated();
  5109. return this;
  5110. };
  5111. /**
  5112. * Adds the current matrix with a second one
  5113. * @param other defines the matrix to add
  5114. * @returns a new matrix as the addition of the current matrix and the given one
  5115. */
  5116. Matrix.prototype.add = function (other) {
  5117. var result = new Matrix();
  5118. this.addToRef(other, result);
  5119. return result;
  5120. };
  5121. /**
  5122. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5123. * @param other defines the matrix to add
  5124. * @param result defines the target matrix
  5125. * @returns the current matrix
  5126. */
  5127. Matrix.prototype.addToRef = function (other, result) {
  5128. for (var index = 0; index < 16; index++) {
  5129. result.m[index] = this.m[index] + other.m[index];
  5130. }
  5131. result._markAsUpdated();
  5132. return this;
  5133. };
  5134. /**
  5135. * Adds in place the given matrix to the current matrix
  5136. * @param other defines the second operand
  5137. * @returns the current updated matrix
  5138. */
  5139. Matrix.prototype.addToSelf = function (other) {
  5140. for (var index = 0; index < 16; index++) {
  5141. this.m[index] += other.m[index];
  5142. }
  5143. this._markAsUpdated();
  5144. return this;
  5145. };
  5146. /**
  5147. * Sets the given matrix to the current inverted Matrix
  5148. * @param other defines the target matrix
  5149. * @returns the unmodified current matrix
  5150. */
  5151. Matrix.prototype.invertToRef = function (other) {
  5152. var l1 = this.m[0];
  5153. var l2 = this.m[1];
  5154. var l3 = this.m[2];
  5155. var l4 = this.m[3];
  5156. var l5 = this.m[4];
  5157. var l6 = this.m[5];
  5158. var l7 = this.m[6];
  5159. var l8 = this.m[7];
  5160. var l9 = this.m[8];
  5161. var l10 = this.m[9];
  5162. var l11 = this.m[10];
  5163. var l12 = this.m[11];
  5164. var l13 = this.m[12];
  5165. var l14 = this.m[13];
  5166. var l15 = this.m[14];
  5167. var l16 = this.m[15];
  5168. var l17 = (l11 * l16) - (l12 * l15);
  5169. var l18 = (l10 * l16) - (l12 * l14);
  5170. var l19 = (l10 * l15) - (l11 * l14);
  5171. var l20 = (l9 * l16) - (l12 * l13);
  5172. var l21 = (l9 * l15) - (l11 * l13);
  5173. var l22 = (l9 * l14) - (l10 * l13);
  5174. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5175. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5176. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5177. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5178. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5179. var l28 = (l7 * l16) - (l8 * l15);
  5180. var l29 = (l6 * l16) - (l8 * l14);
  5181. var l30 = (l6 * l15) - (l7 * l14);
  5182. var l31 = (l5 * l16) - (l8 * l13);
  5183. var l32 = (l5 * l15) - (l7 * l13);
  5184. var l33 = (l5 * l14) - (l6 * l13);
  5185. var l34 = (l7 * l12) - (l8 * l11);
  5186. var l35 = (l6 * l12) - (l8 * l10);
  5187. var l36 = (l6 * l11) - (l7 * l10);
  5188. var l37 = (l5 * l12) - (l8 * l9);
  5189. var l38 = (l5 * l11) - (l7 * l9);
  5190. var l39 = (l5 * l10) - (l6 * l9);
  5191. other.m[0] = l23 * l27;
  5192. other.m[4] = l24 * l27;
  5193. other.m[8] = l25 * l27;
  5194. other.m[12] = l26 * l27;
  5195. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5196. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5197. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5198. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5199. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5200. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5201. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5202. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5203. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5204. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5205. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5206. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5207. other._markAsUpdated();
  5208. return this;
  5209. };
  5210. /**
  5211. * Inserts the translation vector (using 3 floats) in the current matrix
  5212. * @param x defines the 1st component of the translation
  5213. * @param y defines the 2nd component of the translation
  5214. * @param z defines the 3rd component of the translation
  5215. * @returns the current updated matrix
  5216. */
  5217. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5218. this.m[12] = x;
  5219. this.m[13] = y;
  5220. this.m[14] = z;
  5221. this._markAsUpdated();
  5222. return this;
  5223. };
  5224. /**
  5225. * Inserts the translation vector in the current matrix
  5226. * @param vector3 defines the translation to insert
  5227. * @returns the current updated matrix
  5228. */
  5229. Matrix.prototype.setTranslation = function (vector3) {
  5230. this.m[12] = vector3.x;
  5231. this.m[13] = vector3.y;
  5232. this.m[14] = vector3.z;
  5233. this._markAsUpdated();
  5234. return this;
  5235. };
  5236. /**
  5237. * Gets the translation value of the current matrix
  5238. * @returns a new Vector3 as the extracted translation from the matrix
  5239. */
  5240. Matrix.prototype.getTranslation = function () {
  5241. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5242. };
  5243. /**
  5244. * Fill a Vector3 with the extracted translation from the matrix
  5245. * @param result defines the Vector3 where to store the translation
  5246. * @returns the current matrix
  5247. */
  5248. Matrix.prototype.getTranslationToRef = function (result) {
  5249. result.x = this.m[12];
  5250. result.y = this.m[13];
  5251. result.z = this.m[14];
  5252. return this;
  5253. };
  5254. /**
  5255. * Remove rotation and scaling part from the matrix
  5256. * @returns the updated matrix
  5257. */
  5258. Matrix.prototype.removeRotationAndScaling = function () {
  5259. this.setRowFromFloats(0, 1, 0, 0, 0);
  5260. this.setRowFromFloats(1, 0, 1, 0, 0);
  5261. this.setRowFromFloats(2, 0, 0, 1, 0);
  5262. return this;
  5263. };
  5264. /**
  5265. * Multiply two matrices
  5266. * @param other defines the second operand
  5267. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5268. */
  5269. Matrix.prototype.multiply = function (other) {
  5270. var result = new Matrix();
  5271. this.multiplyToRef(other, result);
  5272. return result;
  5273. };
  5274. /**
  5275. * Copy the current matrix from the given one
  5276. * @param other defines the source matrix
  5277. * @returns the current updated matrix
  5278. */
  5279. Matrix.prototype.copyFrom = function (other) {
  5280. for (var index = 0; index < 16; index++) {
  5281. this.m[index] = other.m[index];
  5282. }
  5283. this._markAsUpdated();
  5284. return this;
  5285. };
  5286. /**
  5287. * Populates the given array from the starting index with the current matrix values
  5288. * @param array defines the target array
  5289. * @param offset defines the offset in the target array where to start storing values
  5290. * @returns the current matrix
  5291. */
  5292. Matrix.prototype.copyToArray = function (array, offset) {
  5293. if (offset === void 0) { offset = 0; }
  5294. for (var index = 0; index < 16; index++) {
  5295. array[offset + index] = this.m[index];
  5296. }
  5297. return this;
  5298. };
  5299. /**
  5300. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5301. * @param other defines the second operand
  5302. * @param result defines the matrix where to store the multiplication
  5303. * @returns the current matrix
  5304. */
  5305. Matrix.prototype.multiplyToRef = function (other, result) {
  5306. this.multiplyToArray(other, result.m, 0);
  5307. result._markAsUpdated();
  5308. return this;
  5309. };
  5310. /**
  5311. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5312. * @param other defines the second operand
  5313. * @param result defines the array where to store the multiplication
  5314. * @param offset defines the offset in the target array where to start storing values
  5315. * @returns the current matrix
  5316. */
  5317. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5318. var tm0 = this.m[0];
  5319. var tm1 = this.m[1];
  5320. var tm2 = this.m[2];
  5321. var tm3 = this.m[3];
  5322. var tm4 = this.m[4];
  5323. var tm5 = this.m[5];
  5324. var tm6 = this.m[6];
  5325. var tm7 = this.m[7];
  5326. var tm8 = this.m[8];
  5327. var tm9 = this.m[9];
  5328. var tm10 = this.m[10];
  5329. var tm11 = this.m[11];
  5330. var tm12 = this.m[12];
  5331. var tm13 = this.m[13];
  5332. var tm14 = this.m[14];
  5333. var tm15 = this.m[15];
  5334. var om0 = other.m[0];
  5335. var om1 = other.m[1];
  5336. var om2 = other.m[2];
  5337. var om3 = other.m[3];
  5338. var om4 = other.m[4];
  5339. var om5 = other.m[5];
  5340. var om6 = other.m[6];
  5341. var om7 = other.m[7];
  5342. var om8 = other.m[8];
  5343. var om9 = other.m[9];
  5344. var om10 = other.m[10];
  5345. var om11 = other.m[11];
  5346. var om12 = other.m[12];
  5347. var om13 = other.m[13];
  5348. var om14 = other.m[14];
  5349. var om15 = other.m[15];
  5350. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5351. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5352. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5353. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5354. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5355. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5356. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5357. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5358. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5359. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5360. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5361. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5362. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5363. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5364. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5365. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5366. return this;
  5367. };
  5368. /**
  5369. * Check equality between this matrix and a second one
  5370. * @param value defines the second matrix to compare
  5371. * @returns true is the current matrix and the given one values are strictly equal
  5372. */
  5373. Matrix.prototype.equals = function (value) {
  5374. return value &&
  5375. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5376. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5377. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5378. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5379. };
  5380. /**
  5381. * Clone the current matrix
  5382. * @returns a new matrix from the current matrix
  5383. */
  5384. Matrix.prototype.clone = function () {
  5385. 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]);
  5386. };
  5387. /**
  5388. * Returns the name of the current matrix class
  5389. * @returns the string "Matrix"
  5390. */
  5391. Matrix.prototype.getClassName = function () {
  5392. return "Matrix";
  5393. };
  5394. /**
  5395. * Gets the hash code of the current matrix
  5396. * @returns the hash code
  5397. */
  5398. Matrix.prototype.getHashCode = function () {
  5399. var hash = this.m[0] || 0;
  5400. for (var i = 1; i < 16; i++) {
  5401. hash = (hash * 397) ^ (this.m[i] || 0);
  5402. }
  5403. return hash;
  5404. };
  5405. /**
  5406. * Decomposes the current Matrix into a translation, rotation and scaling components
  5407. * @param scale defines the scale vector3 given as a reference to update
  5408. * @param rotation defines the rotation quaternion given as a reference to update
  5409. * @param translation defines the translation vector3 given as a reference to update
  5410. * @returns true if operation was successful
  5411. */
  5412. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5413. if (translation) {
  5414. translation.x = this.m[12];
  5415. translation.y = this.m[13];
  5416. translation.z = this.m[14];
  5417. }
  5418. scale = scale || MathTmp.Vector3[0];
  5419. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5420. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5421. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5422. if (this.determinant() <= 0) {
  5423. scale.y *= -1;
  5424. }
  5425. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5426. if (rotation) {
  5427. rotation.x = 0;
  5428. rotation.y = 0;
  5429. rotation.z = 0;
  5430. rotation.w = 1;
  5431. }
  5432. return false;
  5433. }
  5434. if (rotation) {
  5435. 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]);
  5436. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5437. }
  5438. return true;
  5439. };
  5440. /**
  5441. * Gets specific row of the matrix
  5442. * @param index defines the number of the row to get
  5443. * @returns the index-th row of the current matrix as a new Vector4
  5444. */
  5445. Matrix.prototype.getRow = function (index) {
  5446. if (index < 0 || index > 3) {
  5447. return null;
  5448. }
  5449. var i = index * 4;
  5450. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5451. };
  5452. /**
  5453. * Sets the index-th row of the current matrix to the vector4 values
  5454. * @param index defines the number of the row to set
  5455. * @param row defines the target vector4
  5456. * @returns the updated current matrix
  5457. */
  5458. Matrix.prototype.setRow = function (index, row) {
  5459. if (index < 0 || index > 3) {
  5460. return this;
  5461. }
  5462. var i = index * 4;
  5463. this.m[i + 0] = row.x;
  5464. this.m[i + 1] = row.y;
  5465. this.m[i + 2] = row.z;
  5466. this.m[i + 3] = row.w;
  5467. this._markAsUpdated();
  5468. return this;
  5469. };
  5470. /**
  5471. * Compute the transpose of the matrix
  5472. * @returns the new transposed matrix
  5473. */
  5474. Matrix.prototype.transpose = function () {
  5475. return Matrix.Transpose(this);
  5476. };
  5477. /**
  5478. * Compute the transpose of the matrix and store it in a given matrix
  5479. * @param result defines the target matrix
  5480. * @returns the current matrix
  5481. */
  5482. Matrix.prototype.transposeToRef = function (result) {
  5483. Matrix.TransposeToRef(this, result);
  5484. return this;
  5485. };
  5486. /**
  5487. * Sets the index-th row of the current matrix with the given 4 x float values
  5488. * @param index defines the row index
  5489. * @param x defines the x component to set
  5490. * @param y defines the y component to set
  5491. * @param z defines the z component to set
  5492. * @param w defines the w component to set
  5493. * @returns the updated current matrix
  5494. */
  5495. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5496. if (index < 0 || index > 3) {
  5497. return this;
  5498. }
  5499. var i = index * 4;
  5500. this.m[i + 0] = x;
  5501. this.m[i + 1] = y;
  5502. this.m[i + 2] = z;
  5503. this.m[i + 3] = w;
  5504. this._markAsUpdated();
  5505. return this;
  5506. };
  5507. /**
  5508. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5509. * @param scale defines the scale factor
  5510. * @returns a new matrix
  5511. */
  5512. Matrix.prototype.scale = function (scale) {
  5513. var result = new Matrix();
  5514. this.scaleToRef(scale, result);
  5515. return result;
  5516. };
  5517. /**
  5518. * Scale the current matrix values by a factor to a given result matrix
  5519. * @param scale defines the scale factor
  5520. * @param result defines the matrix to store the result
  5521. * @returns the current matrix
  5522. */
  5523. Matrix.prototype.scaleToRef = function (scale, result) {
  5524. for (var index = 0; index < 16; index++) {
  5525. result.m[index] = this.m[index] * scale;
  5526. }
  5527. result._markAsUpdated();
  5528. return this;
  5529. };
  5530. /**
  5531. * Scale the current matrix values by a factor and add the result to a given matrix
  5532. * @param scale defines the scale factor
  5533. * @param result defines the Matrix to store the result
  5534. * @returns the current matrix
  5535. */
  5536. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5537. for (var index = 0; index < 16; index++) {
  5538. result.m[index] += this.m[index] * scale;
  5539. }
  5540. result._markAsUpdated();
  5541. return this;
  5542. };
  5543. /**
  5544. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5545. * @param ref matrix to store the result
  5546. */
  5547. Matrix.prototype.toNormalMatrix = function (ref) {
  5548. this.invertToRef(ref);
  5549. ref.transpose();
  5550. var m = ref.m;
  5551. 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);
  5552. };
  5553. /**
  5554. * Gets only rotation part of the current matrix
  5555. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5556. */
  5557. Matrix.prototype.getRotationMatrix = function () {
  5558. var result = Matrix.Identity();
  5559. this.getRotationMatrixToRef(result);
  5560. return result;
  5561. };
  5562. /**
  5563. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5564. * @param result defines the target matrix to store data to
  5565. * @returns the current matrix
  5566. */
  5567. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5568. var m = this.m;
  5569. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5570. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5571. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5572. if (this.determinant() <= 0) {
  5573. sy *= -1;
  5574. }
  5575. if (sx === 0 || sy === 0 || sz === 0) {
  5576. Matrix.IdentityToRef(result);
  5577. }
  5578. else {
  5579. 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);
  5580. }
  5581. return this;
  5582. };
  5583. // Statics
  5584. /**
  5585. * Creates a matrix from an array
  5586. * @param array defines the source array
  5587. * @param offset defines an offset in the source array
  5588. * @returns a new Matrix set from the starting index of the given array
  5589. */
  5590. Matrix.FromArray = function (array, offset) {
  5591. var result = new Matrix();
  5592. if (!offset) {
  5593. offset = 0;
  5594. }
  5595. Matrix.FromArrayToRef(array, offset, result);
  5596. return result;
  5597. };
  5598. /**
  5599. * Copy the content of an array into a given matrix
  5600. * @param array defines the source array
  5601. * @param offset defines an offset in the source array
  5602. * @param result defines the target matrix
  5603. */
  5604. Matrix.FromArrayToRef = function (array, offset, result) {
  5605. for (var index = 0; index < 16; index++) {
  5606. result.m[index] = array[index + offset];
  5607. }
  5608. result._markAsUpdated();
  5609. };
  5610. /**
  5611. * Stores an array into a matrix after having multiplied each component by a given factor
  5612. * @param array defines the source array
  5613. * @param offset defines the offset in the source array
  5614. * @param scale defines the scaling factor
  5615. * @param result defines the target matrix
  5616. */
  5617. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5618. for (var index = 0; index < 16; index++) {
  5619. result.m[index] = array[index + offset] * scale;
  5620. }
  5621. result._markAsUpdated();
  5622. };
  5623. /**
  5624. * Stores a list of values (16) inside a given matrix
  5625. * @param initialM11 defines 1st value of 1st row
  5626. * @param initialM12 defines 2nd value of 1st row
  5627. * @param initialM13 defines 3rd value of 1st row
  5628. * @param initialM14 defines 4th value of 1st row
  5629. * @param initialM21 defines 1st value of 2nd row
  5630. * @param initialM22 defines 2nd value of 2nd row
  5631. * @param initialM23 defines 3rd value of 2nd row
  5632. * @param initialM24 defines 4th value of 2nd row
  5633. * @param initialM31 defines 1st value of 3rd row
  5634. * @param initialM32 defines 2nd value of 3rd row
  5635. * @param initialM33 defines 3rd value of 3rd row
  5636. * @param initialM34 defines 4th value of 3rd row
  5637. * @param initialM41 defines 1st value of 4th row
  5638. * @param initialM42 defines 2nd value of 4th row
  5639. * @param initialM43 defines 3rd value of 4th row
  5640. * @param initialM44 defines 4th value of 4th row
  5641. * @param result defines the target matrix
  5642. */
  5643. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5644. result.m[0] = initialM11;
  5645. result.m[1] = initialM12;
  5646. result.m[2] = initialM13;
  5647. result.m[3] = initialM14;
  5648. result.m[4] = initialM21;
  5649. result.m[5] = initialM22;
  5650. result.m[6] = initialM23;
  5651. result.m[7] = initialM24;
  5652. result.m[8] = initialM31;
  5653. result.m[9] = initialM32;
  5654. result.m[10] = initialM33;
  5655. result.m[11] = initialM34;
  5656. result.m[12] = initialM41;
  5657. result.m[13] = initialM42;
  5658. result.m[14] = initialM43;
  5659. result.m[15] = initialM44;
  5660. result._markAsUpdated();
  5661. };
  5662. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5663. /**
  5664. * Gets an identity matrix that must not be updated
  5665. */
  5666. get: function () {
  5667. return Matrix._identityReadOnly;
  5668. },
  5669. enumerable: true,
  5670. configurable: true
  5671. });
  5672. /**
  5673. * Creates new matrix from a list of values (16)
  5674. * @param initialM11 defines 1st value of 1st row
  5675. * @param initialM12 defines 2nd value of 1st row
  5676. * @param initialM13 defines 3rd value of 1st row
  5677. * @param initialM14 defines 4th value of 1st row
  5678. * @param initialM21 defines 1st value of 2nd row
  5679. * @param initialM22 defines 2nd value of 2nd row
  5680. * @param initialM23 defines 3rd value of 2nd row
  5681. * @param initialM24 defines 4th value of 2nd row
  5682. * @param initialM31 defines 1st value of 3rd row
  5683. * @param initialM32 defines 2nd value of 3rd row
  5684. * @param initialM33 defines 3rd value of 3rd row
  5685. * @param initialM34 defines 4th value of 3rd row
  5686. * @param initialM41 defines 1st value of 4th row
  5687. * @param initialM42 defines 2nd value of 4th row
  5688. * @param initialM43 defines 3rd value of 4th row
  5689. * @param initialM44 defines 4th value of 4th row
  5690. * @returns the new matrix
  5691. */
  5692. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5693. var result = new Matrix();
  5694. result.m[0] = initialM11;
  5695. result.m[1] = initialM12;
  5696. result.m[2] = initialM13;
  5697. result.m[3] = initialM14;
  5698. result.m[4] = initialM21;
  5699. result.m[5] = initialM22;
  5700. result.m[6] = initialM23;
  5701. result.m[7] = initialM24;
  5702. result.m[8] = initialM31;
  5703. result.m[9] = initialM32;
  5704. result.m[10] = initialM33;
  5705. result.m[11] = initialM34;
  5706. result.m[12] = initialM41;
  5707. result.m[13] = initialM42;
  5708. result.m[14] = initialM43;
  5709. result.m[15] = initialM44;
  5710. return result;
  5711. };
  5712. /**
  5713. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5714. * @param scale defines the scale vector3
  5715. * @param rotation defines the rotation quaternion
  5716. * @param translation defines the translation vector3
  5717. * @returns a new matrix
  5718. */
  5719. Matrix.Compose = function (scale, rotation, translation) {
  5720. var result = Matrix.Identity();
  5721. Matrix.ComposeToRef(scale, rotation, translation, result);
  5722. return result;
  5723. };
  5724. /**
  5725. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5726. * @param scale defines the scale vector3
  5727. * @param rotation defines the rotation quaternion
  5728. * @param translation defines the translation vector3
  5729. * @param result defines the target matrix
  5730. */
  5731. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5732. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5733. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5734. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5735. result.setTranslation(translation);
  5736. };
  5737. /**
  5738. * Creates a new identity matrix
  5739. * @returns a new identity matrix
  5740. */
  5741. Matrix.Identity = function () {
  5742. 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);
  5743. };
  5744. /**
  5745. * Creates a new identity matrix and stores the result in a given matrix
  5746. * @param result defines the target matrix
  5747. */
  5748. Matrix.IdentityToRef = function (result) {
  5749. 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);
  5750. };
  5751. /**
  5752. * Creates a new zero matrix
  5753. * @returns a new zero matrix
  5754. */
  5755. Matrix.Zero = function () {
  5756. 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);
  5757. };
  5758. /**
  5759. * Creates a new rotation matrix for "angle" radians around the X axis
  5760. * @param angle defines the angle (in radians) to use
  5761. * @return the new matrix
  5762. */
  5763. Matrix.RotationX = function (angle) {
  5764. var result = new Matrix();
  5765. Matrix.RotationXToRef(angle, result);
  5766. return result;
  5767. };
  5768. /**
  5769. * Creates a new matrix as the invert of a given matrix
  5770. * @param source defines the source matrix
  5771. * @returns the new matrix
  5772. */
  5773. Matrix.Invert = function (source) {
  5774. var result = new Matrix();
  5775. source.invertToRef(result);
  5776. return result;
  5777. };
  5778. /**
  5779. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5780. * @param angle defines the angle (in radians) to use
  5781. * @param result defines the target matrix
  5782. */
  5783. Matrix.RotationXToRef = function (angle, result) {
  5784. var s = Math.sin(angle);
  5785. var c = Math.cos(angle);
  5786. result.m[0] = 1.0;
  5787. result.m[15] = 1.0;
  5788. result.m[5] = c;
  5789. result.m[10] = c;
  5790. result.m[9] = -s;
  5791. result.m[6] = s;
  5792. result.m[1] = 0.0;
  5793. result.m[2] = 0.0;
  5794. result.m[3] = 0.0;
  5795. result.m[4] = 0.0;
  5796. result.m[7] = 0.0;
  5797. result.m[8] = 0.0;
  5798. result.m[11] = 0.0;
  5799. result.m[12] = 0.0;
  5800. result.m[13] = 0.0;
  5801. result.m[14] = 0.0;
  5802. result._markAsUpdated();
  5803. };
  5804. /**
  5805. * Creates a new rotation matrix for "angle" radians around the Y axis
  5806. * @param angle defines the angle (in radians) to use
  5807. * @return the new matrix
  5808. */
  5809. Matrix.RotationY = function (angle) {
  5810. var result = new Matrix();
  5811. Matrix.RotationYToRef(angle, result);
  5812. return result;
  5813. };
  5814. /**
  5815. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5816. * @param angle defines the angle (in radians) to use
  5817. * @param result defines the target matrix
  5818. */
  5819. Matrix.RotationYToRef = function (angle, result) {
  5820. var s = Math.sin(angle);
  5821. var c = Math.cos(angle);
  5822. result.m[5] = 1.0;
  5823. result.m[15] = 1.0;
  5824. result.m[0] = c;
  5825. result.m[2] = -s;
  5826. result.m[8] = s;
  5827. result.m[10] = c;
  5828. result.m[1] = 0.0;
  5829. result.m[3] = 0.0;
  5830. result.m[4] = 0.0;
  5831. result.m[6] = 0.0;
  5832. result.m[7] = 0.0;
  5833. result.m[9] = 0.0;
  5834. result.m[11] = 0.0;
  5835. result.m[12] = 0.0;
  5836. result.m[13] = 0.0;
  5837. result.m[14] = 0.0;
  5838. result._markAsUpdated();
  5839. };
  5840. /**
  5841. * Creates a new rotation matrix for "angle" radians around the Z axis
  5842. * @param angle defines the angle (in radians) to use
  5843. * @return the new matrix
  5844. */
  5845. Matrix.RotationZ = function (angle) {
  5846. var result = new Matrix();
  5847. Matrix.RotationZToRef(angle, result);
  5848. return result;
  5849. };
  5850. /**
  5851. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5852. * @param angle defines the angle (in radians) to use
  5853. * @param result defines the target matrix
  5854. */
  5855. Matrix.RotationZToRef = function (angle, result) {
  5856. var s = Math.sin(angle);
  5857. var c = Math.cos(angle);
  5858. result.m[10] = 1.0;
  5859. result.m[15] = 1.0;
  5860. result.m[0] = c;
  5861. result.m[1] = s;
  5862. result.m[4] = -s;
  5863. result.m[5] = c;
  5864. result.m[2] = 0.0;
  5865. result.m[3] = 0.0;
  5866. result.m[6] = 0.0;
  5867. result.m[7] = 0.0;
  5868. result.m[8] = 0.0;
  5869. result.m[9] = 0.0;
  5870. result.m[11] = 0.0;
  5871. result.m[12] = 0.0;
  5872. result.m[13] = 0.0;
  5873. result.m[14] = 0.0;
  5874. result._markAsUpdated();
  5875. };
  5876. /**
  5877. * Creates a new rotation matrix for "angle" radians around the given axis
  5878. * @param axis defines the axis to use
  5879. * @param angle defines the angle (in radians) to use
  5880. * @return the new matrix
  5881. */
  5882. Matrix.RotationAxis = function (axis, angle) {
  5883. var result = Matrix.Zero();
  5884. Matrix.RotationAxisToRef(axis, angle, result);
  5885. return result;
  5886. };
  5887. /**
  5888. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5889. * @param axis defines the axis to use
  5890. * @param angle defines the angle (in radians) to use
  5891. * @param result defines the target matrix
  5892. */
  5893. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5894. var s = Math.sin(-angle);
  5895. var c = Math.cos(-angle);
  5896. var c1 = 1 - c;
  5897. axis.normalize();
  5898. result.m[0] = (axis.x * axis.x) * c1 + c;
  5899. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5900. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5901. result.m[3] = 0.0;
  5902. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5903. result.m[5] = (axis.y * axis.y) * c1 + c;
  5904. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5905. result.m[7] = 0.0;
  5906. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5907. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5908. result.m[10] = (axis.z * axis.z) * c1 + c;
  5909. result.m[11] = 0.0;
  5910. result.m[15] = 1.0;
  5911. result._markAsUpdated();
  5912. };
  5913. /**
  5914. * Creates a rotation matrix
  5915. * @param yaw defines the yaw angle in radians (Y axis)
  5916. * @param pitch defines the pitch angle in radians (X axis)
  5917. * @param roll defines the roll angle in radians (X axis)
  5918. * @returns the new rotation matrix
  5919. */
  5920. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5921. var result = new Matrix();
  5922. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5923. return result;
  5924. };
  5925. /**
  5926. * Creates a rotation matrix and stores it in a given matrix
  5927. * @param yaw defines the yaw angle in radians (Y axis)
  5928. * @param pitch defines the pitch angle in radians (X axis)
  5929. * @param roll defines the roll angle in radians (X axis)
  5930. * @param result defines the target matrix
  5931. */
  5932. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5933. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5934. this._tempQuaternion.toRotationMatrix(result);
  5935. };
  5936. /**
  5937. * Creates a scaling matrix
  5938. * @param x defines the scale factor on X axis
  5939. * @param y defines the scale factor on Y axis
  5940. * @param z defines the scale factor on Z axis
  5941. * @returns the new matrix
  5942. */
  5943. Matrix.Scaling = function (x, y, z) {
  5944. var result = Matrix.Zero();
  5945. Matrix.ScalingToRef(x, y, z, result);
  5946. return result;
  5947. };
  5948. /**
  5949. * Creates a scaling matrix and stores it in a given matrix
  5950. * @param x defines the scale factor on X axis
  5951. * @param y defines the scale factor on Y axis
  5952. * @param z defines the scale factor on Z axis
  5953. * @param result defines the target matrix
  5954. */
  5955. Matrix.ScalingToRef = function (x, y, z, result) {
  5956. result.m[0] = x;
  5957. result.m[1] = 0.0;
  5958. result.m[2] = 0.0;
  5959. result.m[3] = 0.0;
  5960. result.m[4] = 0.0;
  5961. result.m[5] = y;
  5962. result.m[6] = 0.0;
  5963. result.m[7] = 0.0;
  5964. result.m[8] = 0.0;
  5965. result.m[9] = 0.0;
  5966. result.m[10] = z;
  5967. result.m[11] = 0.0;
  5968. result.m[12] = 0.0;
  5969. result.m[13] = 0.0;
  5970. result.m[14] = 0.0;
  5971. result.m[15] = 1.0;
  5972. result._markAsUpdated();
  5973. };
  5974. /**
  5975. * Creates a translation matrix
  5976. * @param x defines the translation on X axis
  5977. * @param y defines the translation on Y axis
  5978. * @param z defines the translationon Z axis
  5979. * @returns the new matrix
  5980. */
  5981. Matrix.Translation = function (x, y, z) {
  5982. var result = Matrix.Identity();
  5983. Matrix.TranslationToRef(x, y, z, result);
  5984. return result;
  5985. };
  5986. /**
  5987. * Creates a translation matrix and stores it in a given matrix
  5988. * @param x defines the translation on X axis
  5989. * @param y defines the translation on Y axis
  5990. * @param z defines the translationon Z axis
  5991. * @param result defines the target matrix
  5992. */
  5993. Matrix.TranslationToRef = function (x, y, z, result) {
  5994. 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);
  5995. };
  5996. /**
  5997. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5998. * @param startValue defines the start value
  5999. * @param endValue defines the end value
  6000. * @param gradient defines the gradient factor
  6001. * @returns the new matrix
  6002. */
  6003. Matrix.Lerp = function (startValue, endValue, gradient) {
  6004. var result = Matrix.Zero();
  6005. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6006. return result;
  6007. };
  6008. /**
  6009. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6010. * @param startValue defines the start value
  6011. * @param endValue defines the end value
  6012. * @param gradient defines the gradient factor
  6013. * @param result defines the Matrix object where to store data
  6014. */
  6015. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6016. for (var index = 0; index < 16; index++) {
  6017. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6018. }
  6019. result._markAsUpdated();
  6020. };
  6021. /**
  6022. * Builds a new matrix whose values are computed by:
  6023. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6024. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6025. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6026. * @param startValue defines the first matrix
  6027. * @param endValue defines the second matrix
  6028. * @param gradient defines the gradient between the two matrices
  6029. * @returns the new matrix
  6030. */
  6031. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6032. var result = Matrix.Zero();
  6033. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6034. return result;
  6035. };
  6036. /**
  6037. * Update a matrix to values which are computed by:
  6038. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6039. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6040. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6041. * @param startValue defines the first matrix
  6042. * @param endValue defines the second matrix
  6043. * @param gradient defines the gradient between the two matrices
  6044. * @param result defines the target matrix
  6045. */
  6046. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6047. var startScale = MathTmp.Vector3[0];
  6048. var startRotation = MathTmp.Quaternion[0];
  6049. var startTranslation = MathTmp.Vector3[1];
  6050. startValue.decompose(startScale, startRotation, startTranslation);
  6051. var endScale = MathTmp.Vector3[2];
  6052. var endRotation = MathTmp.Quaternion[1];
  6053. var endTranslation = MathTmp.Vector3[3];
  6054. endValue.decompose(endScale, endRotation, endTranslation);
  6055. var resultScale = MathTmp.Vector3[4];
  6056. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6057. var resultRotation = MathTmp.Quaternion[2];
  6058. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6059. var resultTranslation = MathTmp.Vector3[5];
  6060. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6061. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6062. };
  6063. /**
  6064. * 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"
  6065. * This function works in left handed mode
  6066. * @param eye defines the final position of the entity
  6067. * @param target defines where the entity should look at
  6068. * @param up defines the up vector for the entity
  6069. * @returns the new matrix
  6070. */
  6071. Matrix.LookAtLH = function (eye, target, up) {
  6072. var result = Matrix.Zero();
  6073. Matrix.LookAtLHToRef(eye, target, up, result);
  6074. return result;
  6075. };
  6076. /**
  6077. * 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".
  6078. * This function works in left handed mode
  6079. * @param eye defines the final position of the entity
  6080. * @param target defines where the entity should look at
  6081. * @param up defines the up vector for the entity
  6082. * @param result defines the target matrix
  6083. */
  6084. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6085. // Z axis
  6086. target.subtractToRef(eye, this._zAxis);
  6087. this._zAxis.normalize();
  6088. // X axis
  6089. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6090. if (this._xAxis.lengthSquared() === 0) {
  6091. this._xAxis.x = 1.0;
  6092. }
  6093. else {
  6094. this._xAxis.normalize();
  6095. }
  6096. // Y axis
  6097. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6098. this._yAxis.normalize();
  6099. // Eye angles
  6100. var ex = -Vector3.Dot(this._xAxis, eye);
  6101. var ey = -Vector3.Dot(this._yAxis, eye);
  6102. var ez = -Vector3.Dot(this._zAxis, eye);
  6103. 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);
  6104. };
  6105. /**
  6106. * 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"
  6107. * This function works in right handed mode
  6108. * @param eye defines the final position of the entity
  6109. * @param target defines where the entity should look at
  6110. * @param up defines the up vector for the entity
  6111. * @returns the new matrix
  6112. */
  6113. Matrix.LookAtRH = function (eye, target, up) {
  6114. var result = Matrix.Zero();
  6115. Matrix.LookAtRHToRef(eye, target, up, result);
  6116. return result;
  6117. };
  6118. /**
  6119. * 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".
  6120. * This function works in right handed mode
  6121. * @param eye defines the final position of the entity
  6122. * @param target defines where the entity should look at
  6123. * @param up defines the up vector for the entity
  6124. * @param result defines the target matrix
  6125. */
  6126. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6127. // Z axis
  6128. eye.subtractToRef(target, this._zAxis);
  6129. this._zAxis.normalize();
  6130. // X axis
  6131. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6132. if (this._xAxis.lengthSquared() === 0) {
  6133. this._xAxis.x = 1.0;
  6134. }
  6135. else {
  6136. this._xAxis.normalize();
  6137. }
  6138. // Y axis
  6139. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6140. this._yAxis.normalize();
  6141. // Eye angles
  6142. var ex = -Vector3.Dot(this._xAxis, eye);
  6143. var ey = -Vector3.Dot(this._yAxis, eye);
  6144. var ez = -Vector3.Dot(this._zAxis, eye);
  6145. 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);
  6146. };
  6147. /**
  6148. * Create a left-handed orthographic projection matrix
  6149. * @param width defines the viewport width
  6150. * @param height defines the viewport height
  6151. * @param znear defines the near clip plane
  6152. * @param zfar defines the far clip plane
  6153. * @returns a new matrix as a left-handed orthographic projection matrix
  6154. */
  6155. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6156. var matrix = Matrix.Zero();
  6157. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6158. return matrix;
  6159. };
  6160. /**
  6161. * Store a left-handed orthographic projection to a given matrix
  6162. * @param width defines the viewport width
  6163. * @param height defines the viewport height
  6164. * @param znear defines the near clip plane
  6165. * @param zfar defines the far clip plane
  6166. * @param result defines the target matrix
  6167. */
  6168. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6169. var n = znear;
  6170. var f = zfar;
  6171. var a = 2.0 / width;
  6172. var b = 2.0 / height;
  6173. var c = 2.0 / (f - n);
  6174. var d = -(f + n) / (f - n);
  6175. 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);
  6176. };
  6177. /**
  6178. * Create a left-handed orthographic projection matrix
  6179. * @param left defines the viewport left coordinate
  6180. * @param right defines the viewport right coordinate
  6181. * @param bottom defines the viewport bottom coordinate
  6182. * @param top defines the viewport top coordinate
  6183. * @param znear defines the near clip plane
  6184. * @param zfar defines the far clip plane
  6185. * @returns a new matrix as a left-handed orthographic projection matrix
  6186. */
  6187. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6188. var matrix = Matrix.Zero();
  6189. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6190. return matrix;
  6191. };
  6192. /**
  6193. * Stores a left-handed orthographic projection into a given matrix
  6194. * @param left defines the viewport left coordinate
  6195. * @param right defines the viewport right coordinate
  6196. * @param bottom defines the viewport bottom coordinate
  6197. * @param top defines the viewport top coordinate
  6198. * @param znear defines the near clip plane
  6199. * @param zfar defines the far clip plane
  6200. * @param result defines the target matrix
  6201. */
  6202. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6203. var n = znear;
  6204. var f = zfar;
  6205. var a = 2.0 / (right - left);
  6206. var b = 2.0 / (top - bottom);
  6207. var c = 2.0 / (f - n);
  6208. var d = -(f + n) / (f - n);
  6209. var i0 = (left + right) / (left - right);
  6210. var i1 = (top + bottom) / (bottom - top);
  6211. 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);
  6212. };
  6213. /**
  6214. * Creates a right-handed orthographic projection matrix
  6215. * @param left defines the viewport left coordinate
  6216. * @param right defines the viewport right coordinate
  6217. * @param bottom defines the viewport bottom coordinate
  6218. * @param top defines the viewport top coordinate
  6219. * @param znear defines the near clip plane
  6220. * @param zfar defines the far clip plane
  6221. * @returns a new matrix as a right-handed orthographic projection matrix
  6222. */
  6223. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6224. var matrix = Matrix.Zero();
  6225. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6226. return matrix;
  6227. };
  6228. /**
  6229. * Stores a right-handed orthographic projection into a given matrix
  6230. * @param left defines the viewport left coordinate
  6231. * @param right defines the viewport right coordinate
  6232. * @param bottom defines the viewport bottom coordinate
  6233. * @param top defines the viewport top coordinate
  6234. * @param znear defines the near clip plane
  6235. * @param zfar defines the far clip plane
  6236. * @param result defines the target matrix
  6237. */
  6238. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6239. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6240. result.m[10] *= -1.0;
  6241. };
  6242. /**
  6243. * Creates a left-handed perspective projection matrix
  6244. * @param width defines the viewport width
  6245. * @param height defines the viewport height
  6246. * @param znear defines the near clip plane
  6247. * @param zfar defines the far clip plane
  6248. * @returns a new matrix as a left-handed perspective projection matrix
  6249. */
  6250. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6251. var matrix = Matrix.Zero();
  6252. var n = znear;
  6253. var f = zfar;
  6254. var a = 2.0 * n / width;
  6255. var b = 2.0 * n / height;
  6256. var c = (f + n) / (f - n);
  6257. var d = -2.0 * f * n / (f - n);
  6258. 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);
  6259. return matrix;
  6260. };
  6261. /**
  6262. * Creates a left-handed perspective projection matrix
  6263. * @param fov defines the horizontal field of view
  6264. * @param aspect defines the aspect ratio
  6265. * @param znear defines the near clip plane
  6266. * @param zfar defines the far clip plane
  6267. * @returns a new matrix as a left-handed perspective projection matrix
  6268. */
  6269. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6270. var matrix = Matrix.Zero();
  6271. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6272. return matrix;
  6273. };
  6274. /**
  6275. * Stores a left-handed perspective projection into a given matrix
  6276. * @param fov defines the horizontal field of view
  6277. * @param aspect defines the aspect ratio
  6278. * @param znear defines the near clip plane
  6279. * @param zfar defines the far clip plane
  6280. * @param result defines the target matrix
  6281. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6282. */
  6283. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6284. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6285. var n = znear;
  6286. var f = zfar;
  6287. var t = 1.0 / (Math.tan(fov * 0.5));
  6288. var a = isVerticalFovFixed ? (t / aspect) : t;
  6289. var b = isVerticalFovFixed ? t : (t * aspect);
  6290. var c = (f + n) / (f - n);
  6291. var d = -2.0 * f * n / (f - n);
  6292. 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);
  6293. };
  6294. /**
  6295. * Creates a right-handed perspective projection matrix
  6296. * @param fov defines the horizontal field of view
  6297. * @param aspect defines the aspect ratio
  6298. * @param znear defines the near clip plane
  6299. * @param zfar defines the far clip plane
  6300. * @returns a new matrix as a right-handed perspective projection matrix
  6301. */
  6302. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6303. var matrix = Matrix.Zero();
  6304. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6305. return matrix;
  6306. };
  6307. /**
  6308. * Stores a right-handed perspective projection into a given matrix
  6309. * @param fov defines the horizontal field of view
  6310. * @param aspect defines the aspect ratio
  6311. * @param znear defines the near clip plane
  6312. * @param zfar defines the far clip plane
  6313. * @param result defines the target matrix
  6314. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6315. */
  6316. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6317. //alternatively this could be expressed as:
  6318. // m = PerspectiveFovLHToRef
  6319. // m[10] *= -1.0;
  6320. // m[11] *= -1.0;
  6321. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6322. var n = znear;
  6323. var f = zfar;
  6324. var t = 1.0 / (Math.tan(fov * 0.5));
  6325. var a = isVerticalFovFixed ? (t / aspect) : t;
  6326. var b = isVerticalFovFixed ? t : (t * aspect);
  6327. var c = -(f + n) / (f - n);
  6328. var d = -2 * f * n / (f - n);
  6329. 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);
  6330. };
  6331. /**
  6332. * Stores a perspective projection for WebVR info a given matrix
  6333. * @param fov defines the field of view
  6334. * @param znear defines the near clip plane
  6335. * @param zfar defines the far clip plane
  6336. * @param result defines the target matrix
  6337. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6338. */
  6339. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6340. if (rightHanded === void 0) { rightHanded = false; }
  6341. var rightHandedFactor = rightHanded ? -1 : 1;
  6342. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6343. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6344. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6345. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6346. var xScale = 2.0 / (leftTan + rightTan);
  6347. var yScale = 2.0 / (upTan + downTan);
  6348. result.m[0] = xScale;
  6349. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6350. result.m[5] = yScale;
  6351. result.m[6] = result.m[7] = 0.0;
  6352. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6353. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6354. result.m[10] = -zfar / (znear - zfar);
  6355. result.m[11] = 1.0 * rightHandedFactor;
  6356. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6357. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6358. result._markAsUpdated();
  6359. };
  6360. /**
  6361. * Computes a complete transformation matrix
  6362. * @param viewport defines the viewport to use
  6363. * @param world defines the world matrix
  6364. * @param view defines the view matrix
  6365. * @param projection defines the projection matrix
  6366. * @param zmin defines the near clip plane
  6367. * @param zmax defines the far clip plane
  6368. * @returns the transformation matrix
  6369. */
  6370. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6371. var cw = viewport.width;
  6372. var ch = viewport.height;
  6373. var cx = viewport.x;
  6374. var cy = viewport.y;
  6375. 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);
  6376. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6377. };
  6378. /**
  6379. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6380. * @param matrix defines the matrix to use
  6381. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6382. */
  6383. Matrix.GetAsMatrix2x2 = function (matrix) {
  6384. return new Float32Array([
  6385. matrix.m[0], matrix.m[1],
  6386. matrix.m[4], matrix.m[5]
  6387. ]);
  6388. };
  6389. /**
  6390. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6391. * @param matrix defines the matrix to use
  6392. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6393. */
  6394. Matrix.GetAsMatrix3x3 = function (matrix) {
  6395. return new Float32Array([
  6396. matrix.m[0], matrix.m[1], matrix.m[2],
  6397. matrix.m[4], matrix.m[5], matrix.m[6],
  6398. matrix.m[8], matrix.m[9], matrix.m[10]
  6399. ]);
  6400. };
  6401. /**
  6402. * Compute the transpose of a given matrix
  6403. * @param matrix defines the matrix to transpose
  6404. * @returns the new matrix
  6405. */
  6406. Matrix.Transpose = function (matrix) {
  6407. var result = new Matrix();
  6408. Matrix.TransposeToRef(matrix, result);
  6409. return result;
  6410. };
  6411. /**
  6412. * Compute the transpose of a matrix and store it in a target matrix
  6413. * @param matrix defines the matrix to transpose
  6414. * @param result defines the target matrix
  6415. */
  6416. Matrix.TransposeToRef = function (matrix, result) {
  6417. result.m[0] = matrix.m[0];
  6418. result.m[1] = matrix.m[4];
  6419. result.m[2] = matrix.m[8];
  6420. result.m[3] = matrix.m[12];
  6421. result.m[4] = matrix.m[1];
  6422. result.m[5] = matrix.m[5];
  6423. result.m[6] = matrix.m[9];
  6424. result.m[7] = matrix.m[13];
  6425. result.m[8] = matrix.m[2];
  6426. result.m[9] = matrix.m[6];
  6427. result.m[10] = matrix.m[10];
  6428. result.m[11] = matrix.m[14];
  6429. result.m[12] = matrix.m[3];
  6430. result.m[13] = matrix.m[7];
  6431. result.m[14] = matrix.m[11];
  6432. result.m[15] = matrix.m[15];
  6433. };
  6434. /**
  6435. * Computes a reflection matrix from a plane
  6436. * @param plane defines the reflection plane
  6437. * @returns a new matrix
  6438. */
  6439. Matrix.Reflection = function (plane) {
  6440. var matrix = new Matrix();
  6441. Matrix.ReflectionToRef(plane, matrix);
  6442. return matrix;
  6443. };
  6444. /**
  6445. * Computes a reflection matrix from a plane
  6446. * @param plane defines the reflection plane
  6447. * @param result defines the target matrix
  6448. */
  6449. Matrix.ReflectionToRef = function (plane, result) {
  6450. plane.normalize();
  6451. var x = plane.normal.x;
  6452. var y = plane.normal.y;
  6453. var z = plane.normal.z;
  6454. var temp = -2 * x;
  6455. var temp2 = -2 * y;
  6456. var temp3 = -2 * z;
  6457. result.m[0] = (temp * x) + 1;
  6458. result.m[1] = temp2 * x;
  6459. result.m[2] = temp3 * x;
  6460. result.m[3] = 0.0;
  6461. result.m[4] = temp * y;
  6462. result.m[5] = (temp2 * y) + 1;
  6463. result.m[6] = temp3 * y;
  6464. result.m[7] = 0.0;
  6465. result.m[8] = temp * z;
  6466. result.m[9] = temp2 * z;
  6467. result.m[10] = (temp3 * z) + 1;
  6468. result.m[11] = 0.0;
  6469. result.m[12] = temp * plane.d;
  6470. result.m[13] = temp2 * plane.d;
  6471. result.m[14] = temp3 * plane.d;
  6472. result.m[15] = 1.0;
  6473. result._markAsUpdated();
  6474. };
  6475. /**
  6476. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6477. * @param xaxis defines the value of the 1st axis
  6478. * @param yaxis defines the value of the 2nd axis
  6479. * @param zaxis defines the value of the 3rd axis
  6480. * @param result defines the target matrix
  6481. */
  6482. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6483. result.m[0] = xaxis.x;
  6484. result.m[1] = xaxis.y;
  6485. result.m[2] = xaxis.z;
  6486. result.m[3] = 0.0;
  6487. result.m[4] = yaxis.x;
  6488. result.m[5] = yaxis.y;
  6489. result.m[6] = yaxis.z;
  6490. result.m[7] = 0.0;
  6491. result.m[8] = zaxis.x;
  6492. result.m[9] = zaxis.y;
  6493. result.m[10] = zaxis.z;
  6494. result.m[11] = 0.0;
  6495. result.m[12] = 0.0;
  6496. result.m[13] = 0.0;
  6497. result.m[14] = 0.0;
  6498. result.m[15] = 1.0;
  6499. result._markAsUpdated();
  6500. };
  6501. /**
  6502. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6503. * @param quat defines the quaternion to use
  6504. * @param result defines the target matrix
  6505. */
  6506. Matrix.FromQuaternionToRef = function (quat, result) {
  6507. var xx = quat.x * quat.x;
  6508. var yy = quat.y * quat.y;
  6509. var zz = quat.z * quat.z;
  6510. var xy = quat.x * quat.y;
  6511. var zw = quat.z * quat.w;
  6512. var zx = quat.z * quat.x;
  6513. var yw = quat.y * quat.w;
  6514. var yz = quat.y * quat.z;
  6515. var xw = quat.x * quat.w;
  6516. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6517. result.m[1] = 2.0 * (xy + zw);
  6518. result.m[2] = 2.0 * (zx - yw);
  6519. result.m[3] = 0.0;
  6520. result.m[4] = 2.0 * (xy - zw);
  6521. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6522. result.m[6] = 2.0 * (yz + xw);
  6523. result.m[7] = 0.0;
  6524. result.m[8] = 2.0 * (zx + yw);
  6525. result.m[9] = 2.0 * (yz - xw);
  6526. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6527. result.m[11] = 0.0;
  6528. result.m[12] = 0.0;
  6529. result.m[13] = 0.0;
  6530. result.m[14] = 0.0;
  6531. result.m[15] = 1.0;
  6532. result._markAsUpdated();
  6533. };
  6534. Matrix._tempQuaternion = new Quaternion();
  6535. Matrix._xAxis = Vector3.Zero();
  6536. Matrix._yAxis = Vector3.Zero();
  6537. Matrix._zAxis = Vector3.Zero();
  6538. Matrix._updateFlagSeed = 0;
  6539. Matrix._identityReadOnly = Matrix.Identity();
  6540. return Matrix;
  6541. }());
  6542. BABYLON.Matrix = Matrix;
  6543. var Plane = /** @class */ (function () {
  6544. /**
  6545. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6546. */
  6547. function Plane(a, b, c, d) {
  6548. this.normal = new Vector3(a, b, c);
  6549. this.d = d;
  6550. }
  6551. /**
  6552. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6553. */
  6554. Plane.prototype.asArray = function () {
  6555. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6556. };
  6557. // Methods
  6558. /**
  6559. * Returns a new plane copied from the current Plane.
  6560. */
  6561. Plane.prototype.clone = function () {
  6562. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6563. };
  6564. /**
  6565. * Returns the string "Plane".
  6566. */
  6567. Plane.prototype.getClassName = function () {
  6568. return "Plane";
  6569. };
  6570. /**
  6571. * Returns the Plane hash code.
  6572. */
  6573. Plane.prototype.getHashCode = function () {
  6574. var hash = this.normal.getHashCode();
  6575. hash = (hash * 397) ^ (this.d || 0);
  6576. return hash;
  6577. };
  6578. /**
  6579. * Normalize the current Plane in place.
  6580. * Returns the updated Plane.
  6581. */
  6582. Plane.prototype.normalize = function () {
  6583. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6584. var magnitude = 0.0;
  6585. if (norm !== 0) {
  6586. magnitude = 1.0 / norm;
  6587. }
  6588. this.normal.x *= magnitude;
  6589. this.normal.y *= magnitude;
  6590. this.normal.z *= magnitude;
  6591. this.d *= magnitude;
  6592. return this;
  6593. };
  6594. /**
  6595. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6596. */
  6597. Plane.prototype.transform = function (transformation) {
  6598. var transposedMatrix = Matrix.Transpose(transformation);
  6599. var x = this.normal.x;
  6600. var y = this.normal.y;
  6601. var z = this.normal.z;
  6602. var d = this.d;
  6603. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6604. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6605. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6606. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6607. return new Plane(normalX, normalY, normalZ, finalD);
  6608. };
  6609. /**
  6610. * Returns the dot product (float) of the point coordinates and the plane normal.
  6611. */
  6612. Plane.prototype.dotCoordinate = function (point) {
  6613. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6614. };
  6615. /**
  6616. * Updates the current Plane from the plane defined by the three given points.
  6617. * Returns the updated Plane.
  6618. */
  6619. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6620. var x1 = point2.x - point1.x;
  6621. var y1 = point2.y - point1.y;
  6622. var z1 = point2.z - point1.z;
  6623. var x2 = point3.x - point1.x;
  6624. var y2 = point3.y - point1.y;
  6625. var z2 = point3.z - point1.z;
  6626. var yz = (y1 * z2) - (z1 * y2);
  6627. var xz = (z1 * x2) - (x1 * z2);
  6628. var xy = (x1 * y2) - (y1 * x2);
  6629. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6630. var invPyth;
  6631. if (pyth !== 0) {
  6632. invPyth = 1.0 / pyth;
  6633. }
  6634. else {
  6635. invPyth = 0.0;
  6636. }
  6637. this.normal.x = yz * invPyth;
  6638. this.normal.y = xz * invPyth;
  6639. this.normal.z = xy * invPyth;
  6640. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6641. return this;
  6642. };
  6643. /**
  6644. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6645. */
  6646. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6647. var dot = Vector3.Dot(this.normal, direction);
  6648. return (dot <= epsilon);
  6649. };
  6650. /**
  6651. * Returns the signed distance (float) from the given point to the Plane.
  6652. */
  6653. Plane.prototype.signedDistanceTo = function (point) {
  6654. return Vector3.Dot(point, this.normal) + this.d;
  6655. };
  6656. // Statics
  6657. /**
  6658. * Returns a new Plane from the given array.
  6659. */
  6660. Plane.FromArray = function (array) {
  6661. return new Plane(array[0], array[1], array[2], array[3]);
  6662. };
  6663. /**
  6664. * Returns a new Plane defined by the three given points.
  6665. */
  6666. Plane.FromPoints = function (point1, point2, point3) {
  6667. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6668. result.copyFromPoints(point1, point2, point3);
  6669. return result;
  6670. };
  6671. /**
  6672. * Returns a new Plane the normal vector to this plane at the given origin point.
  6673. * Note : the vector "normal" is updated because normalized.
  6674. */
  6675. Plane.FromPositionAndNormal = function (origin, normal) {
  6676. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6677. normal.normalize();
  6678. result.normal = normal;
  6679. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6680. return result;
  6681. };
  6682. /**
  6683. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6684. */
  6685. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6686. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6687. return Vector3.Dot(point, normal) + d;
  6688. };
  6689. return Plane;
  6690. }());
  6691. BABYLON.Plane = Plane;
  6692. var Viewport = /** @class */ (function () {
  6693. /**
  6694. * Creates a Viewport object located at (x, y) and sized (width, height).
  6695. */
  6696. function Viewport(x, y, width, height) {
  6697. this.x = x;
  6698. this.y = y;
  6699. this.width = width;
  6700. this.height = height;
  6701. }
  6702. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6703. if (renderWidthOrEngine.getRenderWidth) {
  6704. var engine = renderWidthOrEngine;
  6705. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6706. }
  6707. var renderWidth = renderWidthOrEngine;
  6708. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6709. };
  6710. /**
  6711. * Returns a new Viewport copied from the current one.
  6712. */
  6713. Viewport.prototype.clone = function () {
  6714. return new Viewport(this.x, this.y, this.width, this.height);
  6715. };
  6716. return Viewport;
  6717. }());
  6718. BABYLON.Viewport = Viewport;
  6719. var Frustum = /** @class */ (function () {
  6720. function Frustum() {
  6721. }
  6722. /**
  6723. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6724. */
  6725. Frustum.GetPlanes = function (transform) {
  6726. var frustumPlanes = [];
  6727. for (var index = 0; index < 6; index++) {
  6728. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6729. }
  6730. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6731. return frustumPlanes;
  6732. };
  6733. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6734. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6735. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6736. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6737. frustumPlane.d = transform.m[15] + transform.m[14];
  6738. frustumPlane.normalize();
  6739. };
  6740. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6741. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6742. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6743. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6744. frustumPlane.d = transform.m[15] - transform.m[14];
  6745. frustumPlane.normalize();
  6746. };
  6747. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6748. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6749. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6750. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6751. frustumPlane.d = transform.m[15] + transform.m[12];
  6752. frustumPlane.normalize();
  6753. };
  6754. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6755. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6756. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6757. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6758. frustumPlane.d = transform.m[15] - transform.m[12];
  6759. frustumPlane.normalize();
  6760. };
  6761. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6762. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6763. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6764. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6765. frustumPlane.d = transform.m[15] - transform.m[13];
  6766. frustumPlane.normalize();
  6767. };
  6768. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6769. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6770. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6771. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6772. frustumPlane.d = transform.m[15] + transform.m[13];
  6773. frustumPlane.normalize();
  6774. };
  6775. /**
  6776. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6777. */
  6778. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6779. // Near
  6780. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6781. // Far
  6782. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6783. // Left
  6784. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6785. // Right
  6786. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6787. // Top
  6788. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6789. // Bottom
  6790. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6791. };
  6792. return Frustum;
  6793. }());
  6794. BABYLON.Frustum = Frustum;
  6795. /** Defines supported spaces */
  6796. var Space;
  6797. (function (Space) {
  6798. /** Local (object) space */
  6799. Space[Space["LOCAL"] = 0] = "LOCAL";
  6800. /** World space */
  6801. Space[Space["WORLD"] = 1] = "WORLD";
  6802. /** Bone space */
  6803. Space[Space["BONE"] = 2] = "BONE";
  6804. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6805. /** Defines the 3 main axes */
  6806. var Axis = /** @class */ (function () {
  6807. function Axis() {
  6808. }
  6809. /** X axis */
  6810. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6811. /** Y axis */
  6812. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6813. /** Z axis */
  6814. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6815. return Axis;
  6816. }());
  6817. BABYLON.Axis = Axis;
  6818. ;
  6819. var BezierCurve = /** @class */ (function () {
  6820. function BezierCurve() {
  6821. }
  6822. /**
  6823. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6824. */
  6825. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6826. // Extract X (which is equal to time here)
  6827. var f0 = 1 - 3 * x2 + 3 * x1;
  6828. var f1 = 3 * x2 - 6 * x1;
  6829. var f2 = 3 * x1;
  6830. var refinedT = t;
  6831. for (var i = 0; i < 5; i++) {
  6832. var refinedT2 = refinedT * refinedT;
  6833. var refinedT3 = refinedT2 * refinedT;
  6834. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6835. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6836. refinedT -= (x - t) * slope;
  6837. refinedT = Math.min(1, Math.max(0, refinedT));
  6838. }
  6839. // Resolve cubic bezier for the given x
  6840. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6841. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6842. Math.pow(refinedT, 3);
  6843. };
  6844. return BezierCurve;
  6845. }());
  6846. BABYLON.BezierCurve = BezierCurve;
  6847. /**
  6848. * Defines potential orientation for back face culling
  6849. */
  6850. var Orientation;
  6851. (function (Orientation) {
  6852. /**
  6853. * Clockwise
  6854. */
  6855. Orientation[Orientation["CW"] = 0] = "CW";
  6856. /** Counter clockwise */
  6857. Orientation[Orientation["CCW"] = 1] = "CCW";
  6858. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6859. /**
  6860. * Defines angle representation
  6861. */
  6862. var Angle = /** @class */ (function () {
  6863. /**
  6864. * Creates an Angle object of "radians" radians (float).
  6865. */
  6866. function Angle(radians) {
  6867. this._radians = radians;
  6868. if (this._radians < 0.0)
  6869. this._radians += (2.0 * Math.PI);
  6870. }
  6871. /**
  6872. * Get value in degrees
  6873. * @returns the Angle value in degrees (float)
  6874. */
  6875. Angle.prototype.degrees = function () {
  6876. return this._radians * 180.0 / Math.PI;
  6877. };
  6878. /**
  6879. * Get value in radians
  6880. * @returns the Angle value in radians (float)
  6881. */
  6882. Angle.prototype.radians = function () {
  6883. return this._radians;
  6884. };
  6885. /**
  6886. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6887. * @param a defines first vector
  6888. * @param b defines second vector
  6889. * @returns a new Angle
  6890. */
  6891. Angle.BetweenTwoPoints = function (a, b) {
  6892. var delta = b.subtract(a);
  6893. var theta = Math.atan2(delta.y, delta.x);
  6894. return new Angle(theta);
  6895. };
  6896. /**
  6897. * Gets a new Angle object from the given float in radians
  6898. * @param radians defines the angle value in radians
  6899. * @returns a new Angle
  6900. */
  6901. Angle.FromRadians = function (radians) {
  6902. return new Angle(radians);
  6903. };
  6904. /**
  6905. * Gets a new Angle object from the given float in degrees
  6906. * @param degrees defines the angle value in degrees
  6907. * @returns a new Angle
  6908. */
  6909. Angle.FromDegrees = function (degrees) {
  6910. return new Angle(degrees * Math.PI / 180.0);
  6911. };
  6912. return Angle;
  6913. }());
  6914. BABYLON.Angle = Angle;
  6915. var Arc2 = /** @class */ (function () {
  6916. /**
  6917. * Creates an Arc object from the three given points : start, middle and end.
  6918. */
  6919. function Arc2(startPoint, midPoint, endPoint) {
  6920. this.startPoint = startPoint;
  6921. this.midPoint = midPoint;
  6922. this.endPoint = endPoint;
  6923. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6924. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6925. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6926. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6927. 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);
  6928. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6929. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6930. var a1 = this.startAngle.degrees();
  6931. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6932. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6933. // angles correction
  6934. if (a2 - a1 > +180.0)
  6935. a2 -= 360.0;
  6936. if (a2 - a1 < -180.0)
  6937. a2 += 360.0;
  6938. if (a3 - a2 > +180.0)
  6939. a3 -= 360.0;
  6940. if (a3 - a2 < -180.0)
  6941. a3 += 360.0;
  6942. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6943. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6944. }
  6945. return Arc2;
  6946. }());
  6947. BABYLON.Arc2 = Arc2;
  6948. var Path2 = /** @class */ (function () {
  6949. /**
  6950. * Creates a Path2 object from the starting 2D coordinates x and y.
  6951. */
  6952. function Path2(x, y) {
  6953. this._points = new Array();
  6954. this._length = 0.0;
  6955. this.closed = false;
  6956. this._points.push(new Vector2(x, y));
  6957. }
  6958. /**
  6959. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6960. * Returns the updated Path2.
  6961. */
  6962. Path2.prototype.addLineTo = function (x, y) {
  6963. if (this.closed) {
  6964. return this;
  6965. }
  6966. var newPoint = new Vector2(x, y);
  6967. var previousPoint = this._points[this._points.length - 1];
  6968. this._points.push(newPoint);
  6969. this._length += newPoint.subtract(previousPoint).length();
  6970. return this;
  6971. };
  6972. /**
  6973. * 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.
  6974. * Returns the updated Path2.
  6975. */
  6976. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6977. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6978. if (this.closed) {
  6979. return this;
  6980. }
  6981. var startPoint = this._points[this._points.length - 1];
  6982. var midPoint = new Vector2(midX, midY);
  6983. var endPoint = new Vector2(endX, endY);
  6984. var arc = new Arc2(startPoint, midPoint, endPoint);
  6985. var increment = arc.angle.radians() / numberOfSegments;
  6986. if (arc.orientation === Orientation.CW)
  6987. increment *= -1;
  6988. var currentAngle = arc.startAngle.radians() + increment;
  6989. for (var i = 0; i < numberOfSegments; i++) {
  6990. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6991. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6992. this.addLineTo(x, y);
  6993. currentAngle += increment;
  6994. }
  6995. return this;
  6996. };
  6997. /**
  6998. * Closes the Path2.
  6999. * Returns the Path2.
  7000. */
  7001. Path2.prototype.close = function () {
  7002. this.closed = true;
  7003. return this;
  7004. };
  7005. /**
  7006. * Returns the Path2 total length (float).
  7007. */
  7008. Path2.prototype.length = function () {
  7009. var result = this._length;
  7010. if (!this.closed) {
  7011. var lastPoint = this._points[this._points.length - 1];
  7012. var firstPoint = this._points[0];
  7013. result += (firstPoint.subtract(lastPoint).length());
  7014. }
  7015. return result;
  7016. };
  7017. /**
  7018. * Returns the Path2 internal array of points.
  7019. */
  7020. Path2.prototype.getPoints = function () {
  7021. return this._points;
  7022. };
  7023. /**
  7024. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7025. */
  7026. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7027. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7028. return Vector2.Zero();
  7029. }
  7030. var lengthPosition = normalizedLengthPosition * this.length();
  7031. var previousOffset = 0;
  7032. for (var i = 0; i < this._points.length; i++) {
  7033. var j = (i + 1) % this._points.length;
  7034. var a = this._points[i];
  7035. var b = this._points[j];
  7036. var bToA = b.subtract(a);
  7037. var nextOffset = (bToA.length() + previousOffset);
  7038. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7039. var dir = bToA.normalize();
  7040. var localOffset = lengthPosition - previousOffset;
  7041. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7042. }
  7043. previousOffset = nextOffset;
  7044. }
  7045. return Vector2.Zero();
  7046. };
  7047. /**
  7048. * Returns a new Path2 starting at the coordinates (x, y).
  7049. */
  7050. Path2.StartingAt = function (x, y) {
  7051. return new Path2(x, y);
  7052. };
  7053. return Path2;
  7054. }());
  7055. BABYLON.Path2 = Path2;
  7056. var Path3D = /** @class */ (function () {
  7057. /**
  7058. * new Path3D(path, normal, raw)
  7059. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7060. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7061. * path : an array of Vector3, the curve axis of the Path3D
  7062. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7063. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7064. */
  7065. function Path3D(path, firstNormal, raw) {
  7066. if (firstNormal === void 0) { firstNormal = null; }
  7067. this.path = path;
  7068. this._curve = new Array();
  7069. this._distances = new Array();
  7070. this._tangents = new Array();
  7071. this._normals = new Array();
  7072. this._binormals = new Array();
  7073. for (var p = 0; p < path.length; p++) {
  7074. this._curve[p] = path[p].clone(); // hard copy
  7075. }
  7076. this._raw = raw || false;
  7077. this._compute(firstNormal);
  7078. }
  7079. /**
  7080. * Returns the Path3D array of successive Vector3 designing its curve.
  7081. */
  7082. Path3D.prototype.getCurve = function () {
  7083. return this._curve;
  7084. };
  7085. /**
  7086. * Returns an array populated with tangent vectors on each Path3D curve point.
  7087. */
  7088. Path3D.prototype.getTangents = function () {
  7089. return this._tangents;
  7090. };
  7091. /**
  7092. * Returns an array populated with normal vectors on each Path3D curve point.
  7093. */
  7094. Path3D.prototype.getNormals = function () {
  7095. return this._normals;
  7096. };
  7097. /**
  7098. * Returns an array populated with binormal vectors on each Path3D curve point.
  7099. */
  7100. Path3D.prototype.getBinormals = function () {
  7101. return this._binormals;
  7102. };
  7103. /**
  7104. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7105. */
  7106. Path3D.prototype.getDistances = function () {
  7107. return this._distances;
  7108. };
  7109. /**
  7110. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7111. * Returns the same object updated.
  7112. */
  7113. Path3D.prototype.update = function (path, firstNormal) {
  7114. if (firstNormal === void 0) { firstNormal = null; }
  7115. for (var p = 0; p < path.length; p++) {
  7116. this._curve[p].x = path[p].x;
  7117. this._curve[p].y = path[p].y;
  7118. this._curve[p].z = path[p].z;
  7119. }
  7120. this._compute(firstNormal);
  7121. return this;
  7122. };
  7123. // private function compute() : computes tangents, normals and binormals
  7124. Path3D.prototype._compute = function (firstNormal) {
  7125. var l = this._curve.length;
  7126. // first and last tangents
  7127. this._tangents[0] = this._getFirstNonNullVector(0);
  7128. if (!this._raw) {
  7129. this._tangents[0].normalize();
  7130. }
  7131. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7132. if (!this._raw) {
  7133. this._tangents[l - 1].normalize();
  7134. }
  7135. // normals and binormals at first point : arbitrary vector with _normalVector()
  7136. var tg0 = this._tangents[0];
  7137. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7138. this._normals[0] = pp0;
  7139. if (!this._raw) {
  7140. this._normals[0].normalize();
  7141. }
  7142. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7143. if (!this._raw) {
  7144. this._binormals[0].normalize();
  7145. }
  7146. this._distances[0] = 0.0;
  7147. // normals and binormals : next points
  7148. var prev; // previous vector (segment)
  7149. var cur; // current vector (segment)
  7150. var curTang; // current tangent
  7151. // previous normal
  7152. var prevBinor; // previous binormal
  7153. for (var i = 1; i < l; i++) {
  7154. // tangents
  7155. prev = this._getLastNonNullVector(i);
  7156. if (i < l - 1) {
  7157. cur = this._getFirstNonNullVector(i);
  7158. this._tangents[i] = prev.add(cur);
  7159. this._tangents[i].normalize();
  7160. }
  7161. this._distances[i] = this._distances[i - 1] + prev.length();
  7162. // normals and binormals
  7163. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7164. curTang = this._tangents[i];
  7165. prevBinor = this._binormals[i - 1];
  7166. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7167. if (!this._raw) {
  7168. this._normals[i].normalize();
  7169. }
  7170. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7171. if (!this._raw) {
  7172. this._binormals[i].normalize();
  7173. }
  7174. }
  7175. };
  7176. // private function getFirstNonNullVector(index)
  7177. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7178. Path3D.prototype._getFirstNonNullVector = function (index) {
  7179. var i = 1;
  7180. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7181. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7182. i++;
  7183. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7184. }
  7185. return nNVector;
  7186. };
  7187. // private function getLastNonNullVector(index)
  7188. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7189. Path3D.prototype._getLastNonNullVector = function (index) {
  7190. var i = 1;
  7191. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7192. while (nLVector.length() === 0 && index > i + 1) {
  7193. i++;
  7194. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7195. }
  7196. return nLVector;
  7197. };
  7198. // private function normalVector(v0, vt, va) :
  7199. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7200. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7201. Path3D.prototype._normalVector = function (v0, vt, va) {
  7202. var normal0;
  7203. var tgl = vt.length();
  7204. if (tgl === 0.0) {
  7205. tgl = 1.0;
  7206. }
  7207. if (va === undefined || va === null) {
  7208. var point;
  7209. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7210. point = new Vector3(0.0, -1.0, 0.0);
  7211. }
  7212. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7213. point = new Vector3(1.0, 0.0, 0.0);
  7214. }
  7215. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7216. point = new Vector3(0.0, 0.0, 1.0);
  7217. }
  7218. else {
  7219. point = Vector3.Zero();
  7220. }
  7221. normal0 = Vector3.Cross(vt, point);
  7222. }
  7223. else {
  7224. normal0 = Vector3.Cross(vt, va);
  7225. Vector3.CrossToRef(normal0, vt, normal0);
  7226. }
  7227. normal0.normalize();
  7228. return normal0;
  7229. };
  7230. return Path3D;
  7231. }());
  7232. BABYLON.Path3D = Path3D;
  7233. var Curve3 = /** @class */ (function () {
  7234. /**
  7235. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7236. * A Curve3 is designed from a series of successive Vector3.
  7237. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7238. */
  7239. function Curve3(points) {
  7240. this._length = 0.0;
  7241. this._points = points;
  7242. this._length = this._computeLength(points);
  7243. }
  7244. /**
  7245. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7246. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7247. * @param v1 (Vector3) the control point
  7248. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7249. * @param nbPoints (integer) the wanted number of points in the curve
  7250. */
  7251. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7252. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7253. var bez = new Array();
  7254. var equation = function (t, val0, val1, val2) {
  7255. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7256. return res;
  7257. };
  7258. for (var i = 0; i <= nbPoints; i++) {
  7259. 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)));
  7260. }
  7261. return new Curve3(bez);
  7262. };
  7263. /**
  7264. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7265. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7266. * @param v1 (Vector3) the first control point
  7267. * @param v2 (Vector3) the second control point
  7268. * @param v3 (Vector3) the end point of the Cubic Bezier
  7269. * @param nbPoints (integer) the wanted number of points in the curve
  7270. */
  7271. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7272. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7273. var bez = new Array();
  7274. var equation = function (t, val0, val1, val2, val3) {
  7275. 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;
  7276. return res;
  7277. };
  7278. for (var i = 0; i <= nbPoints; i++) {
  7279. 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)));
  7280. }
  7281. return new Curve3(bez);
  7282. };
  7283. /**
  7284. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7285. * @param p1 (Vector3) the origin point of the Hermite Spline
  7286. * @param t1 (Vector3) the tangent vector at the origin point
  7287. * @param p2 (Vector3) the end point of the Hermite Spline
  7288. * @param t2 (Vector3) the tangent vector at the end point
  7289. * @param nbPoints (integer) the wanted number of points in the curve
  7290. */
  7291. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7292. var hermite = new Array();
  7293. var step = 1.0 / nbPoints;
  7294. for (var i = 0; i <= nbPoints; i++) {
  7295. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7296. }
  7297. return new Curve3(hermite);
  7298. };
  7299. /**
  7300. * Returns a Curve3 object along a CatmullRom Spline curve :
  7301. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  7302. * @param nbPoints (integer) the wanted number of points between each curve control points.
  7303. */
  7304. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7305. var totalPoints = new Array();
  7306. totalPoints.push(points[0].clone());
  7307. Array.prototype.push.apply(totalPoints, points);
  7308. totalPoints.push(points[points.length - 1].clone());
  7309. var catmullRom = new Array();
  7310. var step = 1.0 / nbPoints;
  7311. var amount = 0.0;
  7312. for (var i = 0; i < totalPoints.length - 3; i++) {
  7313. amount = 0;
  7314. for (var c = 0; c < nbPoints; c++) {
  7315. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7316. amount += step;
  7317. }
  7318. }
  7319. i--;
  7320. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7321. return new Curve3(catmullRom);
  7322. };
  7323. /**
  7324. * Returns the Curve3 stored array of successive Vector3
  7325. */
  7326. Curve3.prototype.getPoints = function () {
  7327. return this._points;
  7328. };
  7329. /**
  7330. * Returns the computed length (float) of the curve.
  7331. */
  7332. Curve3.prototype.length = function () {
  7333. return this._length;
  7334. };
  7335. /**
  7336. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7337. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7338. * curveA and curveB keep unchanged.
  7339. */
  7340. Curve3.prototype.continue = function (curve) {
  7341. var lastPoint = this._points[this._points.length - 1];
  7342. var continuedPoints = this._points.slice();
  7343. var curvePoints = curve.getPoints();
  7344. for (var i = 1; i < curvePoints.length; i++) {
  7345. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7346. }
  7347. var continuedCurve = new Curve3(continuedPoints);
  7348. return continuedCurve;
  7349. };
  7350. Curve3.prototype._computeLength = function (path) {
  7351. var l = 0;
  7352. for (var i = 1; i < path.length; i++) {
  7353. l += (path[i].subtract(path[i - 1])).length();
  7354. }
  7355. return l;
  7356. };
  7357. return Curve3;
  7358. }());
  7359. BABYLON.Curve3 = Curve3;
  7360. // Vertex formats
  7361. var PositionNormalVertex = /** @class */ (function () {
  7362. function PositionNormalVertex(position, normal) {
  7363. if (position === void 0) { position = Vector3.Zero(); }
  7364. if (normal === void 0) { normal = Vector3.Up(); }
  7365. this.position = position;
  7366. this.normal = normal;
  7367. }
  7368. PositionNormalVertex.prototype.clone = function () {
  7369. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7370. };
  7371. return PositionNormalVertex;
  7372. }());
  7373. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7374. var PositionNormalTextureVertex = /** @class */ (function () {
  7375. function PositionNormalTextureVertex(position, normal, uv) {
  7376. if (position === void 0) { position = Vector3.Zero(); }
  7377. if (normal === void 0) { normal = Vector3.Up(); }
  7378. if (uv === void 0) { uv = Vector2.Zero(); }
  7379. this.position = position;
  7380. this.normal = normal;
  7381. this.uv = uv;
  7382. }
  7383. PositionNormalTextureVertex.prototype.clone = function () {
  7384. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7385. };
  7386. return PositionNormalTextureVertex;
  7387. }());
  7388. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7389. // Temporary pre-allocated objects for engine internal use
  7390. // usage in any internal function :
  7391. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7392. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7393. var Tmp = /** @class */ (function () {
  7394. function Tmp() {
  7395. }
  7396. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7397. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7398. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7399. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7400. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7401. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7402. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7403. Matrix.Zero(), Matrix.Zero(),
  7404. Matrix.Zero(), Matrix.Zero(),
  7405. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7406. return Tmp;
  7407. }());
  7408. BABYLON.Tmp = Tmp;
  7409. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7410. var MathTmp = /** @class */ (function () {
  7411. function MathTmp() {
  7412. }
  7413. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7414. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7415. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7416. return MathTmp;
  7417. }());
  7418. })(BABYLON || (BABYLON = {}));
  7419. //# sourceMappingURL=babylon.math.js.map
  7420. var BABYLON;
  7421. (function (BABYLON) {
  7422. var Scalar = /** @class */ (function () {
  7423. function Scalar() {
  7424. }
  7425. /**
  7426. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7427. */
  7428. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7429. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7430. var num = a - b;
  7431. return -epsilon <= num && num <= epsilon;
  7432. };
  7433. /**
  7434. * Returns a string : the upper case translation of the number i to hexadecimal.
  7435. */
  7436. Scalar.ToHex = function (i) {
  7437. var str = i.toString(16);
  7438. if (i <= 15) {
  7439. return ("0" + str).toUpperCase();
  7440. }
  7441. return str.toUpperCase();
  7442. };
  7443. /**
  7444. * Returns -1 if value is negative and +1 is value is positive.
  7445. * Returns the value itself if it's equal to zero.
  7446. */
  7447. Scalar.Sign = function (value) {
  7448. value = +value; // convert to a number
  7449. if (value === 0 || isNaN(value))
  7450. return value;
  7451. return value > 0 ? 1 : -1;
  7452. };
  7453. /**
  7454. * Returns the value itself if it's between min and max.
  7455. * Returns min if the value is lower than min.
  7456. * Returns max if the value is greater than max.
  7457. */
  7458. Scalar.Clamp = function (value, min, max) {
  7459. if (min === void 0) { min = 0; }
  7460. if (max === void 0) { max = 1; }
  7461. return Math.min(max, Math.max(min, value));
  7462. };
  7463. /**
  7464. * Returns the log2 of value.
  7465. */
  7466. Scalar.Log2 = function (value) {
  7467. return Math.log(value) * Math.LOG2E;
  7468. };
  7469. /**
  7470. * Loops the value, so that it is never larger than length and never smaller than 0.
  7471. *
  7472. * This is similar to the modulo operator but it works with floating point numbers.
  7473. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7474. * With t = 5 and length = 2.5, the result would be 0.0.
  7475. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7476. */
  7477. Scalar.Repeat = function (value, length) {
  7478. return value - Math.floor(value / length) * length;
  7479. };
  7480. /**
  7481. * Normalize the value between 0.0 and 1.0 using min and max values
  7482. */
  7483. Scalar.Normalize = function (value, min, max) {
  7484. return (value - min) / (max - min);
  7485. };
  7486. /**
  7487. * Denormalize the value from 0.0 and 1.0 using min and max values
  7488. */
  7489. Scalar.Denormalize = function (normalized, min, max) {
  7490. return (normalized * (max - min) + min);
  7491. };
  7492. /**
  7493. * Calculates the shortest difference between two given angles given in degrees.
  7494. */
  7495. Scalar.DeltaAngle = function (current, target) {
  7496. var num = Scalar.Repeat(target - current, 360.0);
  7497. if (num > 180.0) {
  7498. num -= 360.0;
  7499. }
  7500. return num;
  7501. };
  7502. /**
  7503. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7504. *
  7505. * The returned value will move back and forth between 0 and length
  7506. */
  7507. Scalar.PingPong = function (tx, length) {
  7508. var t = Scalar.Repeat(tx, length * 2.0);
  7509. return length - Math.abs(t - length);
  7510. };
  7511. /**
  7512. * Interpolates between min and max with smoothing at the limits.
  7513. *
  7514. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7515. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7516. */
  7517. Scalar.SmoothStep = function (from, to, tx) {
  7518. var t = Scalar.Clamp(tx);
  7519. t = -2.0 * t * t * t + 3.0 * t * t;
  7520. return to * t + from * (1.0 - t);
  7521. };
  7522. /**
  7523. * Moves a value current towards target.
  7524. *
  7525. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7526. * Negative values of maxDelta pushes the value away from target.
  7527. */
  7528. Scalar.MoveTowards = function (current, target, maxDelta) {
  7529. var result = 0;
  7530. if (Math.abs(target - current) <= maxDelta) {
  7531. result = target;
  7532. }
  7533. else {
  7534. result = current + Scalar.Sign(target - current) * maxDelta;
  7535. }
  7536. return result;
  7537. };
  7538. /**
  7539. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7540. *
  7541. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7542. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7543. */
  7544. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7545. var num = Scalar.DeltaAngle(current, target);
  7546. var result = 0;
  7547. if (-maxDelta < num && num < maxDelta) {
  7548. result = target;
  7549. }
  7550. else {
  7551. target = current + num;
  7552. result = Scalar.MoveTowards(current, target, maxDelta);
  7553. }
  7554. return result;
  7555. };
  7556. /**
  7557. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7558. */
  7559. Scalar.Lerp = function (start, end, amount) {
  7560. return start + ((end - start) * amount);
  7561. };
  7562. /**
  7563. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7564. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7565. */
  7566. Scalar.LerpAngle = function (start, end, amount) {
  7567. var num = Scalar.Repeat(end - start, 360.0);
  7568. if (num > 180.0) {
  7569. num -= 360.0;
  7570. }
  7571. return start + num * Scalar.Clamp(amount);
  7572. };
  7573. /**
  7574. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7575. */
  7576. Scalar.InverseLerp = function (a, b, value) {
  7577. var result = 0;
  7578. if (a != b) {
  7579. result = Scalar.Clamp((value - a) / (b - a));
  7580. }
  7581. else {
  7582. result = 0.0;
  7583. }
  7584. return result;
  7585. };
  7586. /**
  7587. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7588. */
  7589. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7590. var squared = amount * amount;
  7591. var cubed = amount * squared;
  7592. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7593. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7594. var part3 = (cubed - (2.0 * squared)) + amount;
  7595. var part4 = cubed - squared;
  7596. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7597. };
  7598. /**
  7599. * Returns a random float number between and min and max values
  7600. */
  7601. Scalar.RandomRange = function (min, max) {
  7602. if (min === max)
  7603. return min;
  7604. return ((Math.random() * (max - min)) + min);
  7605. };
  7606. /**
  7607. * This function returns percentage of a number in a given range.
  7608. *
  7609. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7610. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7611. */
  7612. Scalar.RangeToPercent = function (number, min, max) {
  7613. return ((number - min) / (max - min));
  7614. };
  7615. /**
  7616. * This function returns number that corresponds to the percentage in a given range.
  7617. *
  7618. * PercentToRange(0.34,0,100) will return 34.
  7619. */
  7620. Scalar.PercentToRange = function (percent, min, max) {
  7621. return ((max - min) * percent + min);
  7622. };
  7623. /**
  7624. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7625. * @param angle The angle to normalize in radian.
  7626. * @return The converted angle.
  7627. */
  7628. Scalar.NormalizeRadians = function (angle) {
  7629. // More precise but slower version kept for reference.
  7630. // angle = angle % Tools.TwoPi;
  7631. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7632. //if (angle > Math.PI) {
  7633. // angle -= Tools.TwoPi;
  7634. //}
  7635. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7636. return angle;
  7637. };
  7638. /**
  7639. * Two pi constants convenient for computation.
  7640. */
  7641. Scalar.TwoPi = Math.PI * 2;
  7642. return Scalar;
  7643. }());
  7644. BABYLON.Scalar = Scalar;
  7645. })(BABYLON || (BABYLON = {}));
  7646. //# sourceMappingURL=babylon.math.scalar.js.map
  7647. //# sourceMappingURL=babylon.mixins.js.map
  7648. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7649. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7650. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7651. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7652. //# sourceMappingURL=babylon.webgl2.js.map
  7653. var BABYLON;
  7654. (function (BABYLON) {
  7655. var __decoratorInitialStore = {};
  7656. var __mergedStore = {};
  7657. var _copySource = function (creationFunction, source, instanciate) {
  7658. var destination = creationFunction();
  7659. // Tags
  7660. if (BABYLON.Tags) {
  7661. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7662. }
  7663. var classStore = getMergedStore(destination);
  7664. // Properties
  7665. for (var property in classStore) {
  7666. var propertyDescriptor = classStore[property];
  7667. var sourceProperty = source[property];
  7668. var propertyType = propertyDescriptor.type;
  7669. if (sourceProperty !== undefined && sourceProperty !== null) {
  7670. switch (propertyType) {
  7671. case 0: // Value
  7672. case 6: // Mesh reference
  7673. case 11: // Camera reference
  7674. destination[property] = sourceProperty;
  7675. break;
  7676. case 1: // Texture
  7677. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7678. break;
  7679. case 2: // Color3
  7680. case 3: // FresnelParameters
  7681. case 4: // Vector2
  7682. case 5: // Vector3
  7683. case 7: // Color Curves
  7684. case 10: // Quaternion
  7685. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7686. break;
  7687. }
  7688. }
  7689. }
  7690. return destination;
  7691. };
  7692. function getDirectStore(target) {
  7693. var classKey = target.getClassName();
  7694. if (!__decoratorInitialStore[classKey]) {
  7695. __decoratorInitialStore[classKey] = {};
  7696. }
  7697. return __decoratorInitialStore[classKey];
  7698. }
  7699. /**
  7700. * Return the list of properties flagged as serializable
  7701. * @param target: host object
  7702. */
  7703. function getMergedStore(target) {
  7704. var classKey = target.getClassName();
  7705. if (__mergedStore[classKey]) {
  7706. return __mergedStore[classKey];
  7707. }
  7708. __mergedStore[classKey] = {};
  7709. var store = __mergedStore[classKey];
  7710. var currentTarget = target;
  7711. var currentKey = classKey;
  7712. while (currentKey) {
  7713. var initialStore = __decoratorInitialStore[currentKey];
  7714. for (var property in initialStore) {
  7715. store[property] = initialStore[property];
  7716. }
  7717. var parent_1 = void 0;
  7718. var done = false;
  7719. do {
  7720. parent_1 = Object.getPrototypeOf(currentTarget);
  7721. if (!parent_1.getClassName) {
  7722. done = true;
  7723. break;
  7724. }
  7725. if (parent_1.getClassName() !== currentKey) {
  7726. break;
  7727. }
  7728. currentTarget = parent_1;
  7729. } while (parent_1);
  7730. if (done) {
  7731. break;
  7732. }
  7733. currentKey = parent_1.getClassName();
  7734. currentTarget = parent_1;
  7735. }
  7736. return store;
  7737. }
  7738. function generateSerializableMember(type, sourceName) {
  7739. return function (target, propertyKey) {
  7740. var classStore = getDirectStore(target);
  7741. if (!classStore[propertyKey]) {
  7742. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7743. }
  7744. };
  7745. }
  7746. function generateExpandMember(setCallback, targetKey) {
  7747. if (targetKey === void 0) { targetKey = null; }
  7748. return function (target, propertyKey) {
  7749. var key = targetKey || ("_" + propertyKey);
  7750. Object.defineProperty(target, propertyKey, {
  7751. get: function () {
  7752. return this[key];
  7753. },
  7754. set: function (value) {
  7755. if (this[key] === value) {
  7756. return;
  7757. }
  7758. this[key] = value;
  7759. target[setCallback].apply(this);
  7760. },
  7761. enumerable: true,
  7762. configurable: true
  7763. });
  7764. };
  7765. }
  7766. function expandToProperty(callback, targetKey) {
  7767. if (targetKey === void 0) { targetKey = null; }
  7768. return generateExpandMember(callback, targetKey);
  7769. }
  7770. BABYLON.expandToProperty = expandToProperty;
  7771. function serialize(sourceName) {
  7772. return generateSerializableMember(0, sourceName); // value member
  7773. }
  7774. BABYLON.serialize = serialize;
  7775. function serializeAsTexture(sourceName) {
  7776. return generateSerializableMember(1, sourceName); // texture member
  7777. }
  7778. BABYLON.serializeAsTexture = serializeAsTexture;
  7779. function serializeAsColor3(sourceName) {
  7780. return generateSerializableMember(2, sourceName); // color3 member
  7781. }
  7782. BABYLON.serializeAsColor3 = serializeAsColor3;
  7783. function serializeAsFresnelParameters(sourceName) {
  7784. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7785. }
  7786. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7787. function serializeAsVector2(sourceName) {
  7788. return generateSerializableMember(4, sourceName); // vector2 member
  7789. }
  7790. BABYLON.serializeAsVector2 = serializeAsVector2;
  7791. function serializeAsVector3(sourceName) {
  7792. return generateSerializableMember(5, sourceName); // vector3 member
  7793. }
  7794. BABYLON.serializeAsVector3 = serializeAsVector3;
  7795. function serializeAsMeshReference(sourceName) {
  7796. return generateSerializableMember(6, sourceName); // mesh reference member
  7797. }
  7798. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7799. function serializeAsColorCurves(sourceName) {
  7800. return generateSerializableMember(7, sourceName); // color curves
  7801. }
  7802. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7803. function serializeAsColor4(sourceName) {
  7804. return generateSerializableMember(8, sourceName); // color 4
  7805. }
  7806. BABYLON.serializeAsColor4 = serializeAsColor4;
  7807. function serializeAsImageProcessingConfiguration(sourceName) {
  7808. return generateSerializableMember(9, sourceName); // image processing
  7809. }
  7810. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7811. function serializeAsQuaternion(sourceName) {
  7812. return generateSerializableMember(10, sourceName); // quaternion member
  7813. }
  7814. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7815. /**
  7816. * Decorator used to define property that can be serialized as reference to a camera
  7817. * @param sourceName defines the name of the property to decorate
  7818. */
  7819. function serializeAsCameraReference(sourceName) {
  7820. return generateSerializableMember(11, sourceName); // camera reference member
  7821. }
  7822. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7823. var SerializationHelper = /** @class */ (function () {
  7824. function SerializationHelper() {
  7825. }
  7826. SerializationHelper.Serialize = function (entity, serializationObject) {
  7827. if (!serializationObject) {
  7828. serializationObject = {};
  7829. }
  7830. // Tags
  7831. if (BABYLON.Tags) {
  7832. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7833. }
  7834. var serializedProperties = getMergedStore(entity);
  7835. // Properties
  7836. for (var property in serializedProperties) {
  7837. var propertyDescriptor = serializedProperties[property];
  7838. var targetPropertyName = propertyDescriptor.sourceName || property;
  7839. var propertyType = propertyDescriptor.type;
  7840. var sourceProperty = entity[property];
  7841. if (sourceProperty !== undefined && sourceProperty !== null) {
  7842. switch (propertyType) {
  7843. case 0: // Value
  7844. serializationObject[targetPropertyName] = sourceProperty;
  7845. break;
  7846. case 1: // Texture
  7847. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7848. break;
  7849. case 2: // Color3
  7850. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7851. break;
  7852. case 3: // FresnelParameters
  7853. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7854. break;
  7855. case 4: // Vector2
  7856. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7857. break;
  7858. case 5: // Vector3
  7859. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7860. break;
  7861. case 6: // Mesh reference
  7862. serializationObject[targetPropertyName] = sourceProperty.id;
  7863. break;
  7864. case 7: // Color Curves
  7865. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7866. break;
  7867. case 8: // Color 4
  7868. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7869. break;
  7870. case 9: // Image Processing
  7871. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7872. break;
  7873. case 10: // Quaternion
  7874. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7875. break;
  7876. case 11: // Camera reference
  7877. serializationObject[targetPropertyName] = sourceProperty.id;
  7878. break;
  7879. }
  7880. }
  7881. }
  7882. return serializationObject;
  7883. };
  7884. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7885. if (rootUrl === void 0) { rootUrl = null; }
  7886. var destination = creationFunction();
  7887. if (!rootUrl) {
  7888. rootUrl = "";
  7889. }
  7890. // Tags
  7891. if (BABYLON.Tags) {
  7892. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7893. }
  7894. var classStore = getMergedStore(destination);
  7895. // Properties
  7896. for (var property in classStore) {
  7897. var propertyDescriptor = classStore[property];
  7898. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7899. var propertyType = propertyDescriptor.type;
  7900. if (sourceProperty !== undefined && sourceProperty !== null) {
  7901. var dest = destination;
  7902. switch (propertyType) {
  7903. case 0: // Value
  7904. dest[property] = sourceProperty;
  7905. break;
  7906. case 1: // Texture
  7907. if (scene) {
  7908. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7909. }
  7910. break;
  7911. case 2: // Color3
  7912. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7913. break;
  7914. case 3: // FresnelParameters
  7915. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7916. break;
  7917. case 4: // Vector2
  7918. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7919. break;
  7920. case 5: // Vector3
  7921. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7922. break;
  7923. case 6: // Mesh reference
  7924. if (scene) {
  7925. dest[property] = scene.getLastMeshByID(sourceProperty);
  7926. }
  7927. break;
  7928. case 7: // Color Curves
  7929. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7930. break;
  7931. case 8: // Color 4
  7932. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7933. break;
  7934. case 9: // Image Processing
  7935. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7936. break;
  7937. case 10: // Quaternion
  7938. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7939. break;
  7940. case 11: // Camera reference
  7941. if (scene) {
  7942. dest[property] = scene.getCameraByID(sourceProperty);
  7943. }
  7944. break;
  7945. }
  7946. }
  7947. }
  7948. return destination;
  7949. };
  7950. SerializationHelper.Clone = function (creationFunction, source) {
  7951. return _copySource(creationFunction, source, false);
  7952. };
  7953. SerializationHelper.Instanciate = function (creationFunction, source) {
  7954. return _copySource(creationFunction, source, true);
  7955. };
  7956. return SerializationHelper;
  7957. }());
  7958. BABYLON.SerializationHelper = SerializationHelper;
  7959. })(BABYLON || (BABYLON = {}));
  7960. //# sourceMappingURL=babylon.decorators.js.map
  7961. var BABYLON;
  7962. (function (BABYLON) {
  7963. /**
  7964. * Wrapper class for promise with external resolve and reject.
  7965. */
  7966. var Deferred = /** @class */ (function () {
  7967. /**
  7968. * Constructor for this deferred object.
  7969. */
  7970. function Deferred() {
  7971. var _this = this;
  7972. this.promise = new Promise(function (resolve, reject) {
  7973. _this._resolve = resolve;
  7974. _this._reject = reject;
  7975. });
  7976. }
  7977. Object.defineProperty(Deferred.prototype, "resolve", {
  7978. /**
  7979. * The resolve method of the promise associated with this deferred object.
  7980. */
  7981. get: function () {
  7982. return this._resolve;
  7983. },
  7984. enumerable: true,
  7985. configurable: true
  7986. });
  7987. Object.defineProperty(Deferred.prototype, "reject", {
  7988. /**
  7989. * The reject method of the promise associated with this deferred object.
  7990. */
  7991. get: function () {
  7992. return this._reject;
  7993. },
  7994. enumerable: true,
  7995. configurable: true
  7996. });
  7997. return Deferred;
  7998. }());
  7999. BABYLON.Deferred = Deferred;
  8000. })(BABYLON || (BABYLON = {}));
  8001. //# sourceMappingURL=babylon.deferred.js.map
  8002. var BABYLON;
  8003. (function (BABYLON) {
  8004. /**
  8005. * A class serves as a medium between the observable and its observers
  8006. */
  8007. var EventState = /** @class */ (function () {
  8008. /**
  8009. * Create a new EventState
  8010. * @param mask defines the mask associated with this state
  8011. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8012. * @param target defines the original target of the state
  8013. * @param currentTarget defines the current target of the state
  8014. */
  8015. function EventState(mask, skipNextObservers, target, currentTarget) {
  8016. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8017. this.initalize(mask, skipNextObservers, target, currentTarget);
  8018. }
  8019. /**
  8020. * Initialize the current event state
  8021. * @param mask defines the mask associated with this state
  8022. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8023. * @param target defines the original target of the state
  8024. * @param currentTarget defines the current target of the state
  8025. * @returns the current event state
  8026. */
  8027. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8028. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8029. this.mask = mask;
  8030. this.skipNextObservers = skipNextObservers;
  8031. this.target = target;
  8032. this.currentTarget = currentTarget;
  8033. return this;
  8034. };
  8035. return EventState;
  8036. }());
  8037. BABYLON.EventState = EventState;
  8038. /**
  8039. * Represent an Observer registered to a given Observable object.
  8040. */
  8041. var Observer = /** @class */ (function () {
  8042. /**
  8043. * Creates a new observer
  8044. * @param callback defines the callback to call when the observer is notified
  8045. * @param mask defines the mask of the observer (used to filter notifications)
  8046. * @param scope defines the current scope used to restore the JS context
  8047. */
  8048. function Observer(
  8049. /**
  8050. * Defines the callback to call when the observer is notified
  8051. */
  8052. callback,
  8053. /**
  8054. * Defines the mask of the observer (used to filter notifications)
  8055. */
  8056. mask,
  8057. /**
  8058. * Defines the current scope used to restore the JS context
  8059. */
  8060. scope) {
  8061. if (scope === void 0) { scope = null; }
  8062. this.callback = callback;
  8063. this.mask = mask;
  8064. this.scope = scope;
  8065. /** @hidden */
  8066. this._willBeUnregistered = false;
  8067. /**
  8068. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8069. */
  8070. this.unregisterOnNextCall = false;
  8071. }
  8072. return Observer;
  8073. }());
  8074. BABYLON.Observer = Observer;
  8075. /**
  8076. * Represent a list of observers registered to multiple Observables object.
  8077. */
  8078. var MultiObserver = /** @class */ (function () {
  8079. function MultiObserver() {
  8080. }
  8081. /**
  8082. * Release associated resources
  8083. */
  8084. MultiObserver.prototype.dispose = function () {
  8085. if (this._observers && this._observables) {
  8086. for (var index = 0; index < this._observers.length; index++) {
  8087. this._observables[index].remove(this._observers[index]);
  8088. }
  8089. }
  8090. this._observers = null;
  8091. this._observables = null;
  8092. };
  8093. /**
  8094. * Raise a callback when one of the observable will notify
  8095. * @param observables defines a list of observables to watch
  8096. * @param callback defines the callback to call on notification
  8097. * @param mask defines the mask used to filter notifications
  8098. * @param scope defines the current scope used to restore the JS context
  8099. * @returns the new MultiObserver
  8100. */
  8101. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8102. if (mask === void 0) { mask = -1; }
  8103. if (scope === void 0) { scope = null; }
  8104. var result = new MultiObserver();
  8105. result._observers = new Array();
  8106. result._observables = observables;
  8107. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8108. var observable = observables_1[_i];
  8109. var observer = observable.add(callback, mask, false, scope);
  8110. if (observer) {
  8111. result._observers.push(observer);
  8112. }
  8113. }
  8114. return result;
  8115. };
  8116. return MultiObserver;
  8117. }());
  8118. BABYLON.MultiObserver = MultiObserver;
  8119. /**
  8120. * The Observable class is a simple implementation of the Observable pattern.
  8121. *
  8122. * 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.
  8123. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8124. * 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).
  8125. * 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.
  8126. */
  8127. var Observable = /** @class */ (function () {
  8128. /**
  8129. * Creates a new observable
  8130. * @param onObserverAdded defines a callback to call when a new observer is added
  8131. */
  8132. function Observable(onObserverAdded) {
  8133. this._observers = new Array();
  8134. this._eventState = new EventState(0);
  8135. if (onObserverAdded) {
  8136. this._onObserverAdded = onObserverAdded;
  8137. }
  8138. }
  8139. /**
  8140. * Create a new Observer with the specified callback
  8141. * @param callback the callback that will be executed for that Observer
  8142. * @param mask the mask used to filter observers
  8143. * @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.
  8144. * @param scope optional scope for the callback to be called from
  8145. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8146. * @returns the new observer created for the callback
  8147. */
  8148. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8149. if (mask === void 0) { mask = -1; }
  8150. if (insertFirst === void 0) { insertFirst = false; }
  8151. if (scope === void 0) { scope = null; }
  8152. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8153. if (!callback) {
  8154. return null;
  8155. }
  8156. var observer = new Observer(callback, mask, scope);
  8157. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8158. if (insertFirst) {
  8159. this._observers.unshift(observer);
  8160. }
  8161. else {
  8162. this._observers.push(observer);
  8163. }
  8164. if (this._onObserverAdded) {
  8165. this._onObserverAdded(observer);
  8166. }
  8167. return observer;
  8168. };
  8169. /**
  8170. * Remove an Observer from the Observable object
  8171. * @param observer the instance of the Observer to remove
  8172. * @returns false if it doesn't belong to this Observable
  8173. */
  8174. Observable.prototype.remove = function (observer) {
  8175. if (!observer) {
  8176. return false;
  8177. }
  8178. var index = this._observers.indexOf(observer);
  8179. if (index !== -1) {
  8180. this._observers.splice(index, 1);
  8181. return true;
  8182. }
  8183. return false;
  8184. };
  8185. /**
  8186. * Remove a callback from the Observable object
  8187. * @param callback the callback to remove
  8188. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8189. * @returns false if it doesn't belong to this Observable
  8190. */
  8191. Observable.prototype.removeCallback = function (callback, scope) {
  8192. for (var index = 0; index < this._observers.length; index++) {
  8193. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8194. this._observers.splice(index, 1);
  8195. return true;
  8196. }
  8197. }
  8198. return false;
  8199. };
  8200. Observable.prototype._deferUnregister = function (observer) {
  8201. var _this = this;
  8202. observer.unregisterOnNextCall = false;
  8203. observer._willBeUnregistered = true;
  8204. BABYLON.Tools.SetImmediate(function () {
  8205. _this.remove(observer);
  8206. });
  8207. };
  8208. /**
  8209. * Notify all Observers by calling their respective callback with the given data
  8210. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8211. * @param eventData defines the data to send to all observers
  8212. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8213. * @param target defines the original target of the state
  8214. * @param currentTarget defines the current target of the state
  8215. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8216. */
  8217. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8218. if (mask === void 0) { mask = -1; }
  8219. if (!this._observers.length) {
  8220. return true;
  8221. }
  8222. var state = this._eventState;
  8223. state.mask = mask;
  8224. state.target = target;
  8225. state.currentTarget = currentTarget;
  8226. state.skipNextObservers = false;
  8227. state.lastReturnValue = eventData;
  8228. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8229. var obs = _a[_i];
  8230. if (obs._willBeUnregistered) {
  8231. continue;
  8232. }
  8233. if (obs.mask & mask) {
  8234. if (obs.scope) {
  8235. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8236. }
  8237. else {
  8238. state.lastReturnValue = obs.callback(eventData, state);
  8239. }
  8240. if (obs.unregisterOnNextCall) {
  8241. this._deferUnregister(obs);
  8242. }
  8243. }
  8244. if (state.skipNextObservers) {
  8245. return false;
  8246. }
  8247. }
  8248. return true;
  8249. };
  8250. /**
  8251. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8252. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8253. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8254. * and it is crucial that all callbacks will be executed.
  8255. * The order of the callbacks is kept, callbacks are not executed parallel.
  8256. *
  8257. * @param eventData The data to be sent to each callback
  8258. * @param mask is used to filter observers defaults to -1
  8259. * @param target defines the callback target (see EventState)
  8260. * @param currentTarget defines he current object in the bubbling phase
  8261. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8262. */
  8263. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8264. var _this = this;
  8265. if (mask === void 0) { mask = -1; }
  8266. // create an empty promise
  8267. var p = Promise.resolve(eventData);
  8268. // no observers? return this promise.
  8269. if (!this._observers.length) {
  8270. return p;
  8271. }
  8272. var state = this._eventState;
  8273. state.mask = mask;
  8274. state.target = target;
  8275. state.currentTarget = currentTarget;
  8276. state.skipNextObservers = false;
  8277. // execute one callback after another (not using Promise.all, the order is important)
  8278. this._observers.forEach(function (obs) {
  8279. if (state.skipNextObservers) {
  8280. return;
  8281. }
  8282. if (obs._willBeUnregistered) {
  8283. return;
  8284. }
  8285. if (obs.mask & mask) {
  8286. if (obs.scope) {
  8287. p = p.then(function (lastReturnedValue) {
  8288. state.lastReturnValue = lastReturnedValue;
  8289. return obs.callback.apply(obs.scope, [eventData, state]);
  8290. });
  8291. }
  8292. else {
  8293. p = p.then(function (lastReturnedValue) {
  8294. state.lastReturnValue = lastReturnedValue;
  8295. return obs.callback(eventData, state);
  8296. });
  8297. }
  8298. if (obs.unregisterOnNextCall) {
  8299. _this._deferUnregister(obs);
  8300. }
  8301. }
  8302. });
  8303. // return the eventData
  8304. return p.then(function () { return eventData; });
  8305. };
  8306. /**
  8307. * Notify a specific observer
  8308. * @param observer defines the observer to notify
  8309. * @param eventData defines the data to be sent to each callback
  8310. * @param mask is used to filter observers defaults to -1
  8311. */
  8312. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8313. if (mask === void 0) { mask = -1; }
  8314. var state = this._eventState;
  8315. state.mask = mask;
  8316. state.skipNextObservers = false;
  8317. observer.callback(eventData, state);
  8318. };
  8319. /**
  8320. * Gets a boolean indicating if the observable has at least one observer
  8321. * @returns true is the Observable has at least one Observer registered
  8322. */
  8323. Observable.prototype.hasObservers = function () {
  8324. return this._observers.length > 0;
  8325. };
  8326. /**
  8327. * Clear the list of observers
  8328. */
  8329. Observable.prototype.clear = function () {
  8330. this._observers = new Array();
  8331. this._onObserverAdded = null;
  8332. };
  8333. /**
  8334. * Clone the current observable
  8335. * @returns a new observable
  8336. */
  8337. Observable.prototype.clone = function () {
  8338. var result = new Observable();
  8339. result._observers = this._observers.slice(0);
  8340. return result;
  8341. };
  8342. /**
  8343. * Does this observable handles observer registered with a given mask
  8344. * @param mask defines the mask to be tested
  8345. * @return whether or not one observer registered with the given mask is handeled
  8346. **/
  8347. Observable.prototype.hasSpecificMask = function (mask) {
  8348. if (mask === void 0) { mask = -1; }
  8349. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8350. var obs = _a[_i];
  8351. if (obs.mask & mask || obs.mask === mask) {
  8352. return true;
  8353. }
  8354. }
  8355. return false;
  8356. };
  8357. return Observable;
  8358. }());
  8359. BABYLON.Observable = Observable;
  8360. })(BABYLON || (BABYLON = {}));
  8361. //# sourceMappingURL=babylon.observable.js.map
  8362. var BABYLON;
  8363. (function (BABYLON) {
  8364. var SmartArray = /** @class */ (function () {
  8365. function SmartArray(capacity) {
  8366. this.length = 0;
  8367. this.data = new Array(capacity);
  8368. this._id = SmartArray._GlobalId++;
  8369. }
  8370. SmartArray.prototype.push = function (value) {
  8371. this.data[this.length++] = value;
  8372. if (this.length > this.data.length) {
  8373. this.data.length *= 2;
  8374. }
  8375. };
  8376. SmartArray.prototype.forEach = function (func) {
  8377. for (var index = 0; index < this.length; index++) {
  8378. func(this.data[index]);
  8379. }
  8380. };
  8381. SmartArray.prototype.sort = function (compareFn) {
  8382. this.data.sort(compareFn);
  8383. };
  8384. SmartArray.prototype.reset = function () {
  8385. this.length = 0;
  8386. };
  8387. SmartArray.prototype.dispose = function () {
  8388. this.reset();
  8389. if (this.data) {
  8390. this.data.length = 0;
  8391. this.data = [];
  8392. }
  8393. };
  8394. SmartArray.prototype.concat = function (array) {
  8395. if (array.length === 0) {
  8396. return;
  8397. }
  8398. if (this.length + array.length > this.data.length) {
  8399. this.data.length = (this.length + array.length) * 2;
  8400. }
  8401. for (var index = 0; index < array.length; index++) {
  8402. this.data[this.length++] = (array.data || array)[index];
  8403. }
  8404. };
  8405. SmartArray.prototype.indexOf = function (value) {
  8406. var position = this.data.indexOf(value);
  8407. if (position >= this.length) {
  8408. return -1;
  8409. }
  8410. return position;
  8411. };
  8412. SmartArray.prototype.contains = function (value) {
  8413. return this.data.indexOf(value) !== -1;
  8414. };
  8415. // Statics
  8416. SmartArray._GlobalId = 0;
  8417. return SmartArray;
  8418. }());
  8419. BABYLON.SmartArray = SmartArray;
  8420. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8421. __extends(SmartArrayNoDuplicate, _super);
  8422. function SmartArrayNoDuplicate() {
  8423. var _this = _super !== null && _super.apply(this, arguments) || this;
  8424. _this._duplicateId = 0;
  8425. return _this;
  8426. }
  8427. SmartArrayNoDuplicate.prototype.push = function (value) {
  8428. _super.prototype.push.call(this, value);
  8429. if (!value.__smartArrayFlags) {
  8430. value.__smartArrayFlags = {};
  8431. }
  8432. value.__smartArrayFlags[this._id] = this._duplicateId;
  8433. };
  8434. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8435. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8436. return false;
  8437. }
  8438. this.push(value);
  8439. return true;
  8440. };
  8441. SmartArrayNoDuplicate.prototype.reset = function () {
  8442. _super.prototype.reset.call(this);
  8443. this._duplicateId++;
  8444. };
  8445. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8446. if (array.length === 0) {
  8447. return;
  8448. }
  8449. if (this.length + array.length > this.data.length) {
  8450. this.data.length = (this.length + array.length) * 2;
  8451. }
  8452. for (var index = 0; index < array.length; index++) {
  8453. var item = (array.data || array)[index];
  8454. this.pushNoDuplicate(item);
  8455. }
  8456. };
  8457. return SmartArrayNoDuplicate;
  8458. }(SmartArray));
  8459. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8460. })(BABYLON || (BABYLON = {}));
  8461. //# sourceMappingURL=babylon.smartArray.js.map
  8462. var BABYLON;
  8463. (function (BABYLON) {
  8464. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8465. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8466. var LoadFileError = /** @class */ (function (_super) {
  8467. __extends(LoadFileError, _super);
  8468. function LoadFileError(message, request) {
  8469. var _this = _super.call(this, message) || this;
  8470. _this.request = request;
  8471. _this.name = "LoadFileError";
  8472. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8473. return _this;
  8474. }
  8475. // Polyfill for Object.setPrototypeOf if necessary.
  8476. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8477. return LoadFileError;
  8478. }(Error));
  8479. BABYLON.LoadFileError = LoadFileError;
  8480. var RetryStrategy = /** @class */ (function () {
  8481. function RetryStrategy() {
  8482. }
  8483. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8484. if (maxRetries === void 0) { maxRetries = 3; }
  8485. if (baseInterval === void 0) { baseInterval = 500; }
  8486. return function (url, request, retryIndex) {
  8487. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8488. return -1;
  8489. }
  8490. return Math.pow(2, retryIndex) * baseInterval;
  8491. };
  8492. };
  8493. return RetryStrategy;
  8494. }());
  8495. BABYLON.RetryStrategy = RetryStrategy;
  8496. // Screenshots
  8497. var screenshotCanvas;
  8498. var cloneValue = function (source, destinationObject) {
  8499. if (!source)
  8500. return null;
  8501. if (source instanceof BABYLON.Mesh) {
  8502. return null;
  8503. }
  8504. if (source instanceof BABYLON.SubMesh) {
  8505. return source.clone(destinationObject);
  8506. }
  8507. else if (source.clone) {
  8508. return source.clone();
  8509. }
  8510. return null;
  8511. };
  8512. var Tools = /** @class */ (function () {
  8513. function Tools() {
  8514. }
  8515. /**
  8516. * Interpolates between a and b via alpha
  8517. * @param a The lower value (returned when alpha = 0)
  8518. * @param b The upper value (returned when alpha = 1)
  8519. * @param alpha The interpolation-factor
  8520. * @return The mixed value
  8521. */
  8522. Tools.Mix = function (a, b, alpha) {
  8523. return a * (1 - alpha) + b * alpha;
  8524. };
  8525. Tools.Instantiate = function (className) {
  8526. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8527. return Tools.RegisteredExternalClasses[className];
  8528. }
  8529. var arr = className.split(".");
  8530. var fn = (window || this);
  8531. for (var i = 0, len = arr.length; i < len; i++) {
  8532. fn = fn[arr[i]];
  8533. }
  8534. if (typeof fn !== "function") {
  8535. return null;
  8536. }
  8537. return fn;
  8538. };
  8539. /**
  8540. * Provides a slice function that will work even on IE
  8541. * @param data defines the array to slice
  8542. * @param start defines the start of the data (optional)
  8543. * @param end defines the end of the data (optional)
  8544. * @returns the new sliced array
  8545. */
  8546. Tools.Slice = function (data, start, end) {
  8547. if (data.slice) {
  8548. return data.slice(start, end);
  8549. }
  8550. return Array.prototype.slice.call(data, start, end);
  8551. };
  8552. Tools.SetImmediate = function (action) {
  8553. if (window.setImmediate) {
  8554. window.setImmediate(action);
  8555. }
  8556. else {
  8557. setTimeout(action, 1);
  8558. }
  8559. };
  8560. Tools.IsExponentOfTwo = function (value) {
  8561. var count = 1;
  8562. do {
  8563. count *= 2;
  8564. } while (count < value);
  8565. return count === value;
  8566. };
  8567. /**
  8568. * Returns the nearest 32-bit single precision float representation of a Number
  8569. * @param value A Number. If the parameter is of a different type, it will get converted
  8570. * to a number or to NaN if it cannot be converted
  8571. * @returns number
  8572. */
  8573. Tools.FloatRound = function (value) {
  8574. if (Math.fround) {
  8575. return Math.fround(value);
  8576. }
  8577. return (Tools._tmpFloatArray[0] = value);
  8578. };
  8579. /**
  8580. * Find the next highest power of two.
  8581. * @param x Number to start search from.
  8582. * @return Next highest power of two.
  8583. */
  8584. Tools.CeilingPOT = function (x) {
  8585. x--;
  8586. x |= x >> 1;
  8587. x |= x >> 2;
  8588. x |= x >> 4;
  8589. x |= x >> 8;
  8590. x |= x >> 16;
  8591. x++;
  8592. return x;
  8593. };
  8594. /**
  8595. * Find the next lowest power of two.
  8596. * @param x Number to start search from.
  8597. * @return Next lowest power of two.
  8598. */
  8599. Tools.FloorPOT = function (x) {
  8600. x = x | (x >> 1);
  8601. x = x | (x >> 2);
  8602. x = x | (x >> 4);
  8603. x = x | (x >> 8);
  8604. x = x | (x >> 16);
  8605. return x - (x >> 1);
  8606. };
  8607. /**
  8608. * Find the nearest power of two.
  8609. * @param x Number to start search from.
  8610. * @return Next nearest power of two.
  8611. */
  8612. Tools.NearestPOT = function (x) {
  8613. var c = Tools.CeilingPOT(x);
  8614. var f = Tools.FloorPOT(x);
  8615. return (c - x) > (x - f) ? f : c;
  8616. };
  8617. Tools.GetExponentOfTwo = function (value, max, mode) {
  8618. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8619. var pot;
  8620. switch (mode) {
  8621. case BABYLON.Engine.SCALEMODE_FLOOR:
  8622. pot = Tools.FloorPOT(value);
  8623. break;
  8624. case BABYLON.Engine.SCALEMODE_NEAREST:
  8625. pot = Tools.NearestPOT(value);
  8626. break;
  8627. case BABYLON.Engine.SCALEMODE_CEILING:
  8628. default:
  8629. pot = Tools.CeilingPOT(value);
  8630. break;
  8631. }
  8632. return Math.min(pot, max);
  8633. };
  8634. Tools.GetFilename = function (path) {
  8635. var index = path.lastIndexOf("/");
  8636. if (index < 0)
  8637. return path;
  8638. return path.substring(index + 1);
  8639. };
  8640. /**
  8641. * Extracts the "folder" part of a path (everything before the filename).
  8642. * @param uri The URI to extract the info from
  8643. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8644. * @returns The "folder" part of the path
  8645. */
  8646. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8647. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8648. var index = uri.lastIndexOf("/");
  8649. if (index < 0) {
  8650. if (returnUnchangedIfNoSlash) {
  8651. return uri;
  8652. }
  8653. return "";
  8654. }
  8655. return uri.substring(0, index + 1);
  8656. };
  8657. Tools.GetDOMTextContent = function (element) {
  8658. var result = "";
  8659. var child = element.firstChild;
  8660. while (child) {
  8661. if (child.nodeType === 3) {
  8662. result += child.textContent;
  8663. }
  8664. child = child.nextSibling;
  8665. }
  8666. return result;
  8667. };
  8668. Tools.ToDegrees = function (angle) {
  8669. return angle * 180 / Math.PI;
  8670. };
  8671. Tools.ToRadians = function (angle) {
  8672. return angle * Math.PI / 180;
  8673. };
  8674. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8675. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8676. var output = "";
  8677. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8678. var i = 0;
  8679. var bytes = new Uint8Array(buffer);
  8680. while (i < bytes.length) {
  8681. chr1 = bytes[i++];
  8682. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8683. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8684. enc1 = chr1 >> 2;
  8685. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8686. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8687. enc4 = chr3 & 63;
  8688. if (isNaN(chr2)) {
  8689. enc3 = enc4 = 64;
  8690. }
  8691. else if (isNaN(chr3)) {
  8692. enc4 = 64;
  8693. }
  8694. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8695. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8696. }
  8697. return "data:image/png;base64," + output;
  8698. };
  8699. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8700. if (bias === void 0) { bias = null; }
  8701. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8702. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8703. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8704. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8705. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8706. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8707. }
  8708. if (bias) {
  8709. minimum.x -= minimum.x * bias.x + bias.y;
  8710. minimum.y -= minimum.y * bias.x + bias.y;
  8711. minimum.z -= minimum.z * bias.x + bias.y;
  8712. maximum.x += maximum.x * bias.x + bias.y;
  8713. maximum.y += maximum.y * bias.x + bias.y;
  8714. maximum.z += maximum.z * bias.x + bias.y;
  8715. }
  8716. return {
  8717. minimum: minimum,
  8718. maximum: maximum
  8719. };
  8720. };
  8721. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8722. if (bias === void 0) { bias = null; }
  8723. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8724. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8725. if (!stride) {
  8726. stride = 3;
  8727. }
  8728. for (var index = start; index < start + count; index++) {
  8729. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8730. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8731. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8732. }
  8733. if (bias) {
  8734. minimum.x -= minimum.x * bias.x + bias.y;
  8735. minimum.y -= minimum.y * bias.x + bias.y;
  8736. minimum.z -= minimum.z * bias.x + bias.y;
  8737. maximum.x += maximum.x * bias.x + bias.y;
  8738. maximum.y += maximum.y * bias.x + bias.y;
  8739. maximum.z += maximum.z * bias.x + bias.y;
  8740. }
  8741. return {
  8742. minimum: minimum,
  8743. maximum: maximum
  8744. };
  8745. };
  8746. Tools.Vector2ArrayFeeder = function (array) {
  8747. return function (index) {
  8748. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8749. var length = isFloatArray ? array.length / 2 : array.length;
  8750. if (index >= length) {
  8751. return null;
  8752. }
  8753. if (isFloatArray) {
  8754. var fa = array;
  8755. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8756. }
  8757. var a = array;
  8758. return a[index];
  8759. };
  8760. };
  8761. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8762. if (bias === void 0) { bias = null; }
  8763. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8764. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8765. var i = 0;
  8766. var cur = feeder(i++);
  8767. while (cur) {
  8768. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8769. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8770. cur = feeder(i++);
  8771. }
  8772. if (bias) {
  8773. minimum.x -= minimum.x * bias.x + bias.y;
  8774. minimum.y -= minimum.y * bias.x + bias.y;
  8775. maximum.x += maximum.x * bias.x + bias.y;
  8776. maximum.y += maximum.y * bias.x + bias.y;
  8777. }
  8778. return {
  8779. minimum: minimum,
  8780. maximum: maximum
  8781. };
  8782. };
  8783. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8784. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8785. return null;
  8786. return Array.isArray(obj) ? obj : [obj];
  8787. };
  8788. // Misc.
  8789. Tools.GetPointerPrefix = function () {
  8790. var eventPrefix = "pointer";
  8791. // Check if pointer events are supported
  8792. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8793. eventPrefix = "mouse";
  8794. }
  8795. return eventPrefix;
  8796. };
  8797. /**
  8798. * @param func - the function to be called
  8799. * @param requester - the object that will request the next frame. Falls back to window.
  8800. */
  8801. Tools.QueueNewFrame = function (func, requester) {
  8802. if (!Tools.IsWindowObjectExist()) {
  8803. return setTimeout(func, 16);
  8804. }
  8805. if (!requester) {
  8806. requester = window;
  8807. }
  8808. if (requester.requestAnimationFrame) {
  8809. return requester.requestAnimationFrame(func);
  8810. }
  8811. else if (requester.msRequestAnimationFrame) {
  8812. return requester.msRequestAnimationFrame(func);
  8813. }
  8814. else if (requester.webkitRequestAnimationFrame) {
  8815. return requester.webkitRequestAnimationFrame(func);
  8816. }
  8817. else if (requester.mozRequestAnimationFrame) {
  8818. return requester.mozRequestAnimationFrame(func);
  8819. }
  8820. else if (requester.oRequestAnimationFrame) {
  8821. return requester.oRequestAnimationFrame(func);
  8822. }
  8823. else {
  8824. return window.setTimeout(func, 16);
  8825. }
  8826. };
  8827. Tools.RequestFullscreen = function (element) {
  8828. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8829. if (!requestFunction)
  8830. return;
  8831. requestFunction.call(element);
  8832. };
  8833. Tools.ExitFullscreen = function () {
  8834. if (document.exitFullscreen) {
  8835. document.exitFullscreen();
  8836. }
  8837. else if (document.mozCancelFullScreen) {
  8838. document.mozCancelFullScreen();
  8839. }
  8840. else if (document.webkitCancelFullScreen) {
  8841. document.webkitCancelFullScreen();
  8842. }
  8843. else if (document.msCancelFullScreen) {
  8844. document.msCancelFullScreen();
  8845. }
  8846. };
  8847. Tools.SetCorsBehavior = function (url, element) {
  8848. if (url && url.indexOf("data:") === 0) {
  8849. return;
  8850. }
  8851. if (Tools.CorsBehavior) {
  8852. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8853. element.crossOrigin = Tools.CorsBehavior;
  8854. }
  8855. else {
  8856. var result = Tools.CorsBehavior(url);
  8857. if (result) {
  8858. element.crossOrigin = result;
  8859. }
  8860. }
  8861. }
  8862. };
  8863. // External files
  8864. Tools.CleanUrl = function (url) {
  8865. url = url.replace(/#/mg, "%23");
  8866. return url;
  8867. };
  8868. Tools.LoadImage = function (url, onLoad, onError, database) {
  8869. if (url instanceof ArrayBuffer) {
  8870. url = Tools.EncodeArrayBufferTobase64(url);
  8871. }
  8872. url = Tools.CleanUrl(url);
  8873. url = Tools.PreprocessUrl(url);
  8874. var img = new Image();
  8875. Tools.SetCorsBehavior(url, img);
  8876. var loadHandler = function () {
  8877. img.removeEventListener("load", loadHandler);
  8878. img.removeEventListener("error", errorHandler);
  8879. onLoad(img);
  8880. };
  8881. var errorHandler = function (err) {
  8882. img.removeEventListener("load", loadHandler);
  8883. img.removeEventListener("error", errorHandler);
  8884. Tools.Error("Error while trying to load image: " + url);
  8885. if (onError) {
  8886. onError("Error while trying to load image: " + url, err);
  8887. }
  8888. };
  8889. img.addEventListener("load", loadHandler);
  8890. img.addEventListener("error", errorHandler);
  8891. var noIndexedDB = function () {
  8892. img.src = url;
  8893. };
  8894. var loadFromIndexedDB = function () {
  8895. if (database) {
  8896. database.loadImageFromDB(url, img);
  8897. }
  8898. };
  8899. //ANY database to do!
  8900. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8901. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8902. }
  8903. else {
  8904. if (url.indexOf("file:") !== -1) {
  8905. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8906. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8907. try {
  8908. var blobURL;
  8909. try {
  8910. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8911. }
  8912. catch (ex) {
  8913. // Chrome doesn't support oneTimeOnly parameter
  8914. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8915. }
  8916. img.src = blobURL;
  8917. }
  8918. catch (e) {
  8919. img.src = "";
  8920. }
  8921. return img;
  8922. }
  8923. }
  8924. noIndexedDB();
  8925. }
  8926. return img;
  8927. };
  8928. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8929. url = Tools.CleanUrl(url);
  8930. url = Tools.PreprocessUrl(url);
  8931. // If file and file input are set
  8932. if (url.indexOf("file:") !== -1) {
  8933. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8934. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8935. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8936. }
  8937. }
  8938. var loadUrl = Tools.BaseUrl + url;
  8939. var aborted = false;
  8940. var fileRequest = {
  8941. onCompleteObservable: new BABYLON.Observable(),
  8942. abort: function () { return aborted = true; },
  8943. };
  8944. var requestFile = function () {
  8945. var request = new XMLHttpRequest();
  8946. var retryHandle = null;
  8947. fileRequest.abort = function () {
  8948. aborted = true;
  8949. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8950. request.abort();
  8951. }
  8952. if (retryHandle !== null) {
  8953. clearTimeout(retryHandle);
  8954. retryHandle = null;
  8955. }
  8956. };
  8957. var retryLoop = function (retryIndex) {
  8958. request.open('GET', loadUrl, true);
  8959. if (useArrayBuffer) {
  8960. request.responseType = "arraybuffer";
  8961. }
  8962. if (onProgress) {
  8963. request.addEventListener("progress", onProgress);
  8964. }
  8965. var onLoadEnd = function () {
  8966. request.removeEventListener("loadend", onLoadEnd);
  8967. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8968. fileRequest.onCompleteObservable.clear();
  8969. };
  8970. request.addEventListener("loadend", onLoadEnd);
  8971. var onReadyStateChange = function () {
  8972. if (aborted) {
  8973. return;
  8974. }
  8975. // In case of undefined state in some browsers.
  8976. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8977. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8978. request.removeEventListener("readystatechange", onReadyStateChange);
  8979. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8980. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8981. return;
  8982. }
  8983. var retryStrategy = Tools.DefaultRetryStrategy;
  8984. if (retryStrategy) {
  8985. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8986. if (waitTime !== -1) {
  8987. // Prevent the request from completing for retry.
  8988. request.removeEventListener("loadend", onLoadEnd);
  8989. request = new XMLHttpRequest();
  8990. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8991. return;
  8992. }
  8993. }
  8994. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8995. if (onError) {
  8996. onError(request, e);
  8997. }
  8998. else {
  8999. throw e;
  9000. }
  9001. }
  9002. };
  9003. request.addEventListener("readystatechange", onReadyStateChange);
  9004. request.send();
  9005. };
  9006. retryLoop(0);
  9007. };
  9008. // Caching all files
  9009. if (database && database.enableSceneOffline) {
  9010. var noIndexedDB_1 = function () {
  9011. if (!aborted) {
  9012. requestFile();
  9013. }
  9014. };
  9015. var loadFromIndexedDB = function () {
  9016. // TODO: database needs to support aborting and should return a IFileRequest
  9017. if (aborted) {
  9018. return;
  9019. }
  9020. if (database) {
  9021. database.loadFileFromDB(url, function (data) {
  9022. if (!aborted) {
  9023. onSuccess(data);
  9024. }
  9025. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9026. }, onProgress ? function (event) {
  9027. if (!aborted) {
  9028. onProgress(event);
  9029. }
  9030. } : undefined, noIndexedDB_1, useArrayBuffer);
  9031. }
  9032. };
  9033. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9034. }
  9035. else {
  9036. requestFile();
  9037. }
  9038. return fileRequest;
  9039. };
  9040. /**
  9041. * Load a script (identified by an url). When the url returns, the
  9042. * content of this file is added into a new script element, attached to the DOM (body element)
  9043. */
  9044. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9045. var head = document.getElementsByTagName('head')[0];
  9046. var script = document.createElement('script');
  9047. script.type = 'text/javascript';
  9048. script.src = scriptUrl;
  9049. script.onload = function () {
  9050. if (onSuccess) {
  9051. onSuccess();
  9052. }
  9053. };
  9054. script.onerror = function (e) {
  9055. if (onError) {
  9056. onError("Unable to load script '" + scriptUrl + "'", e);
  9057. }
  9058. };
  9059. head.appendChild(script);
  9060. };
  9061. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9062. var reader = new FileReader();
  9063. var request = {
  9064. onCompleteObservable: new BABYLON.Observable(),
  9065. abort: function () { return reader.abort(); },
  9066. };
  9067. reader.onloadend = function (e) {
  9068. request.onCompleteObservable.notifyObservers(request);
  9069. };
  9070. reader.onload = function (e) {
  9071. //target doesn't have result from ts 1.3
  9072. callback(e.target['result']);
  9073. };
  9074. reader.onprogress = progressCallback;
  9075. reader.readAsDataURL(fileToLoad);
  9076. return request;
  9077. };
  9078. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9079. var reader = new FileReader();
  9080. var request = {
  9081. onCompleteObservable: new BABYLON.Observable(),
  9082. abort: function () { return reader.abort(); },
  9083. };
  9084. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9085. reader.onerror = function (e) {
  9086. Tools.Log("Error while reading file: " + fileToLoad.name);
  9087. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9088. };
  9089. reader.onload = function (e) {
  9090. //target doesn't have result from ts 1.3
  9091. callback(e.target['result']);
  9092. };
  9093. if (progressCallBack) {
  9094. reader.onprogress = progressCallBack;
  9095. }
  9096. if (!useArrayBuffer) {
  9097. // Asynchronous read
  9098. reader.readAsText(fileToLoad);
  9099. }
  9100. else {
  9101. reader.readAsArrayBuffer(fileToLoad);
  9102. }
  9103. return request;
  9104. };
  9105. //returns a downloadable url to a file content.
  9106. Tools.FileAsURL = function (content) {
  9107. var fileBlob = new Blob([content]);
  9108. var url = window.URL || window.webkitURL;
  9109. var link = url.createObjectURL(fileBlob);
  9110. return link;
  9111. };
  9112. // Misc.
  9113. Tools.Format = function (value, decimals) {
  9114. if (decimals === void 0) { decimals = 2; }
  9115. return value.toFixed(decimals);
  9116. };
  9117. Tools.CheckExtends = function (v, min, max) {
  9118. if (v.x < min.x)
  9119. min.x = v.x;
  9120. if (v.y < min.y)
  9121. min.y = v.y;
  9122. if (v.z < min.z)
  9123. min.z = v.z;
  9124. if (v.x > max.x)
  9125. max.x = v.x;
  9126. if (v.y > max.y)
  9127. max.y = v.y;
  9128. if (v.z > max.z)
  9129. max.z = v.z;
  9130. };
  9131. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9132. for (var prop in source) {
  9133. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9134. continue;
  9135. }
  9136. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9137. continue;
  9138. }
  9139. var sourceValue = source[prop];
  9140. var typeOfSourceValue = typeof sourceValue;
  9141. if (typeOfSourceValue === "function") {
  9142. continue;
  9143. }
  9144. try {
  9145. if (typeOfSourceValue === "object") {
  9146. if (sourceValue instanceof Array) {
  9147. destination[prop] = [];
  9148. if (sourceValue.length > 0) {
  9149. if (typeof sourceValue[0] == "object") {
  9150. for (var index = 0; index < sourceValue.length; index++) {
  9151. var clonedValue = cloneValue(sourceValue[index], destination);
  9152. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9153. destination[prop].push(clonedValue);
  9154. }
  9155. }
  9156. }
  9157. else {
  9158. destination[prop] = sourceValue.slice(0);
  9159. }
  9160. }
  9161. }
  9162. else {
  9163. destination[prop] = cloneValue(sourceValue, destination);
  9164. }
  9165. }
  9166. else {
  9167. destination[prop] = sourceValue;
  9168. }
  9169. }
  9170. catch (e) {
  9171. // Just ignore error (it could be because of a read-only property)
  9172. }
  9173. }
  9174. };
  9175. Tools.IsEmpty = function (obj) {
  9176. for (var i in obj) {
  9177. if (obj.hasOwnProperty(i)) {
  9178. return false;
  9179. }
  9180. }
  9181. return true;
  9182. };
  9183. Tools.RegisterTopRootEvents = function (events) {
  9184. for (var index = 0; index < events.length; index++) {
  9185. var event = events[index];
  9186. window.addEventListener(event.name, event.handler, false);
  9187. try {
  9188. if (window.parent) {
  9189. window.parent.addEventListener(event.name, event.handler, false);
  9190. }
  9191. }
  9192. catch (e) {
  9193. // Silently fails...
  9194. }
  9195. }
  9196. };
  9197. Tools.UnregisterTopRootEvents = function (events) {
  9198. for (var index = 0; index < events.length; index++) {
  9199. var event = events[index];
  9200. window.removeEventListener(event.name, event.handler);
  9201. try {
  9202. if (window.parent) {
  9203. window.parent.removeEventListener(event.name, event.handler);
  9204. }
  9205. }
  9206. catch (e) {
  9207. // Silently fails...
  9208. }
  9209. }
  9210. };
  9211. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9212. if (mimeType === void 0) { mimeType = "image/png"; }
  9213. // Read the contents of the framebuffer
  9214. var numberOfChannelsByLine = width * 4;
  9215. var halfHeight = height / 2;
  9216. //Reading datas from WebGL
  9217. var data = engine.readPixels(0, 0, width, height);
  9218. //To flip image on Y axis.
  9219. for (var i = 0; i < halfHeight; i++) {
  9220. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9221. var currentCell = j + i * numberOfChannelsByLine;
  9222. var targetLine = height - i - 1;
  9223. var targetCell = j + targetLine * numberOfChannelsByLine;
  9224. var temp = data[currentCell];
  9225. data[currentCell] = data[targetCell];
  9226. data[targetCell] = temp;
  9227. }
  9228. }
  9229. // Create a 2D canvas to store the result
  9230. if (!screenshotCanvas) {
  9231. screenshotCanvas = document.createElement('canvas');
  9232. }
  9233. screenshotCanvas.width = width;
  9234. screenshotCanvas.height = height;
  9235. var context = screenshotCanvas.getContext('2d');
  9236. if (context) {
  9237. // Copy the pixels to a 2D canvas
  9238. var imageData = context.createImageData(width, height);
  9239. var castData = (imageData.data);
  9240. castData.set(data);
  9241. context.putImageData(imageData, 0, 0);
  9242. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9243. }
  9244. };
  9245. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9246. if (mimeType === void 0) { mimeType = "image/png"; }
  9247. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9248. if (successCallback) {
  9249. successCallback(base64Image);
  9250. }
  9251. else {
  9252. // We need HTMLCanvasElement.toBlob for HD screenshots
  9253. if (!screenshotCanvas.toBlob) {
  9254. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9255. screenshotCanvas.toBlob = function (callback, type, quality) {
  9256. var _this = this;
  9257. setTimeout(function () {
  9258. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9259. for (var i = 0; i < len; i++) {
  9260. arr[i] = binStr.charCodeAt(i);
  9261. }
  9262. callback(new Blob([arr], { type: type || 'image/png' }));
  9263. });
  9264. };
  9265. }
  9266. screenshotCanvas.toBlob(function (blob) {
  9267. var url = URL.createObjectURL(blob);
  9268. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9269. if (("download" in document.createElement("a"))) {
  9270. var a = window.document.createElement("a");
  9271. a.href = url;
  9272. if (fileName) {
  9273. a.setAttribute("download", fileName);
  9274. }
  9275. else {
  9276. var date = new Date();
  9277. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9278. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9279. }
  9280. window.document.body.appendChild(a);
  9281. a.addEventListener("click", function () {
  9282. if (a.parentElement) {
  9283. a.parentElement.removeChild(a);
  9284. }
  9285. });
  9286. a.click();
  9287. }
  9288. else {
  9289. var newWindow = window.open("");
  9290. if (!newWindow)
  9291. return;
  9292. var img = newWindow.document.createElement("img");
  9293. img.onload = function () {
  9294. // no longer need to read the blob so it's revoked
  9295. URL.revokeObjectURL(url);
  9296. };
  9297. img.src = url;
  9298. newWindow.document.body.appendChild(img);
  9299. }
  9300. });
  9301. }
  9302. };
  9303. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9304. if (mimeType === void 0) { mimeType = "image/png"; }
  9305. var width;
  9306. var height;
  9307. // If a precision value is specified
  9308. if (size.precision) {
  9309. width = Math.round(engine.getRenderWidth() * size.precision);
  9310. height = Math.round(width / engine.getAspectRatio(camera));
  9311. }
  9312. else if (size.width && size.height) {
  9313. width = size.width;
  9314. height = size.height;
  9315. }
  9316. //If passing only width, computing height to keep display canvas ratio.
  9317. else if (size.width && !size.height) {
  9318. width = size.width;
  9319. height = Math.round(width / engine.getAspectRatio(camera));
  9320. }
  9321. //If passing only height, computing width to keep display canvas ratio.
  9322. else if (size.height && !size.width) {
  9323. height = size.height;
  9324. width = Math.round(height * engine.getAspectRatio(camera));
  9325. }
  9326. //Assuming here that "size" parameter is a number
  9327. else if (!isNaN(size)) {
  9328. height = size;
  9329. width = size;
  9330. }
  9331. else {
  9332. Tools.Error("Invalid 'size' parameter !");
  9333. return;
  9334. }
  9335. if (!screenshotCanvas) {
  9336. screenshotCanvas = document.createElement('canvas');
  9337. }
  9338. screenshotCanvas.width = width;
  9339. screenshotCanvas.height = height;
  9340. var renderContext = screenshotCanvas.getContext("2d");
  9341. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9342. var newWidth = width;
  9343. var newHeight = newWidth / ratio;
  9344. if (newHeight > height) {
  9345. newHeight = height;
  9346. newWidth = newHeight * ratio;
  9347. }
  9348. var offsetX = Math.max(0, width - newWidth) / 2;
  9349. var offsetY = Math.max(0, height - newHeight) / 2;
  9350. var renderingCanvas = engine.getRenderingCanvas();
  9351. if (renderContext && renderingCanvas) {
  9352. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9353. }
  9354. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9355. };
  9356. /**
  9357. * Generates an image screenshot from the specified camera.
  9358. *
  9359. * @param engine The engine to use for rendering
  9360. * @param camera The camera to use for rendering
  9361. * @param size This parameter can be set to a single number or to an object with the
  9362. * following (optional) properties: precision, width, height. If a single number is passed,
  9363. * it will be used for both width and height. If an object is passed, the screenshot size
  9364. * will be derived from the parameters. The precision property is a multiplier allowing
  9365. * rendering at a higher or lower resolution.
  9366. * @param successCallback The callback receives a single parameter which contains the
  9367. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9368. * src parameter of an <img> to display it.
  9369. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9370. * Check your browser for supported MIME types.
  9371. * @param samples Texture samples (default: 1)
  9372. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9373. * @param fileName A name for for the downloaded file.
  9374. * @constructor
  9375. */
  9376. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9377. if (mimeType === void 0) { mimeType = "image/png"; }
  9378. if (samples === void 0) { samples = 1; }
  9379. if (antialiasing === void 0) { antialiasing = false; }
  9380. var width;
  9381. var height;
  9382. //If a precision value is specified
  9383. if (size.precision) {
  9384. width = Math.round(engine.getRenderWidth() * size.precision);
  9385. height = Math.round(width / engine.getAspectRatio(camera));
  9386. size = { width: width, height: height };
  9387. }
  9388. else if (size.width && size.height) {
  9389. width = size.width;
  9390. height = size.height;
  9391. }
  9392. //If passing only width, computing height to keep display canvas ratio.
  9393. else if (size.width && !size.height) {
  9394. width = size.width;
  9395. height = Math.round(width / engine.getAspectRatio(camera));
  9396. size = { width: width, height: height };
  9397. }
  9398. //If passing only height, computing width to keep display canvas ratio.
  9399. else if (size.height && !size.width) {
  9400. height = size.height;
  9401. width = Math.round(height * engine.getAspectRatio(camera));
  9402. size = { width: width, height: height };
  9403. }
  9404. //Assuming here that "size" parameter is a number
  9405. else if (!isNaN(size)) {
  9406. height = size;
  9407. width = size;
  9408. }
  9409. else {
  9410. Tools.Error("Invalid 'size' parameter !");
  9411. return;
  9412. }
  9413. var scene = camera.getScene();
  9414. var previousCamera = null;
  9415. if (scene.activeCamera !== camera) {
  9416. previousCamera = scene.activeCamera;
  9417. scene.activeCamera = camera;
  9418. }
  9419. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9420. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9421. texture.renderList = null;
  9422. texture.samples = samples;
  9423. if (antialiasing) {
  9424. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9425. }
  9426. texture.onAfterRenderObservable.add(function () {
  9427. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9428. });
  9429. scene.incrementRenderId();
  9430. scene.resetCachedMaterial();
  9431. texture.render(true);
  9432. texture.dispose();
  9433. if (previousCamera) {
  9434. scene.activeCamera = previousCamera;
  9435. }
  9436. camera.getProjectionMatrix(true); // Force cache refresh;
  9437. };
  9438. // XHR response validator for local file scenario
  9439. Tools.ValidateXHRData = function (xhr, dataType) {
  9440. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9441. if (dataType === void 0) { dataType = 7; }
  9442. try {
  9443. if (dataType & 1) {
  9444. if (xhr.responseText && xhr.responseText.length > 0) {
  9445. return true;
  9446. }
  9447. else if (dataType === 1) {
  9448. return false;
  9449. }
  9450. }
  9451. if (dataType & 2) {
  9452. // Check header width and height since there is no "TGA" magic number
  9453. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9454. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9455. return true;
  9456. }
  9457. else if (dataType === 2) {
  9458. return false;
  9459. }
  9460. }
  9461. if (dataType & 4) {
  9462. // Check for the "DDS" magic number
  9463. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9464. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9465. return true;
  9466. }
  9467. else {
  9468. return false;
  9469. }
  9470. }
  9471. }
  9472. catch (e) {
  9473. // Global protection
  9474. }
  9475. return false;
  9476. };
  9477. /**
  9478. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9479. * Be aware Math.random() could cause collisions, but:
  9480. * "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"
  9481. */
  9482. Tools.RandomId = function () {
  9483. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9484. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9485. return v.toString(16);
  9486. });
  9487. };
  9488. /**
  9489. * Test if the given uri is a base64 string.
  9490. * @param uri The uri to test
  9491. * @return True if the uri is a base64 string or false otherwise.
  9492. */
  9493. Tools.IsBase64 = function (uri) {
  9494. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9495. };
  9496. /**
  9497. * Decode the given base64 uri.
  9498. * @param uri The uri to decode
  9499. * @return The decoded base64 data.
  9500. */
  9501. Tools.DecodeBase64 = function (uri) {
  9502. var decodedString = atob(uri.split(",")[1]);
  9503. var bufferLength = decodedString.length;
  9504. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9505. for (var i = 0; i < bufferLength; i++) {
  9506. bufferView[i] = decodedString.charCodeAt(i);
  9507. }
  9508. return bufferView.buffer;
  9509. };
  9510. Object.defineProperty(Tools, "NoneLogLevel", {
  9511. get: function () {
  9512. return Tools._NoneLogLevel;
  9513. },
  9514. enumerable: true,
  9515. configurable: true
  9516. });
  9517. Object.defineProperty(Tools, "MessageLogLevel", {
  9518. get: function () {
  9519. return Tools._MessageLogLevel;
  9520. },
  9521. enumerable: true,
  9522. configurable: true
  9523. });
  9524. Object.defineProperty(Tools, "WarningLogLevel", {
  9525. get: function () {
  9526. return Tools._WarningLogLevel;
  9527. },
  9528. enumerable: true,
  9529. configurable: true
  9530. });
  9531. Object.defineProperty(Tools, "ErrorLogLevel", {
  9532. get: function () {
  9533. return Tools._ErrorLogLevel;
  9534. },
  9535. enumerable: true,
  9536. configurable: true
  9537. });
  9538. Object.defineProperty(Tools, "AllLogLevel", {
  9539. get: function () {
  9540. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9541. },
  9542. enumerable: true,
  9543. configurable: true
  9544. });
  9545. Tools._AddLogEntry = function (entry) {
  9546. Tools._LogCache = entry + Tools._LogCache;
  9547. if (Tools.OnNewCacheEntry) {
  9548. Tools.OnNewCacheEntry(entry);
  9549. }
  9550. };
  9551. Tools._FormatMessage = function (message) {
  9552. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9553. var date = new Date();
  9554. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9555. };
  9556. Tools._LogDisabled = function (message) {
  9557. // nothing to do
  9558. };
  9559. Tools._LogEnabled = function (message) {
  9560. var formattedMessage = Tools._FormatMessage(message);
  9561. console.log("BJS - " + formattedMessage);
  9562. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9563. Tools._AddLogEntry(entry);
  9564. };
  9565. Tools._WarnDisabled = function (message) {
  9566. // nothing to do
  9567. };
  9568. Tools._WarnEnabled = function (message) {
  9569. var formattedMessage = Tools._FormatMessage(message);
  9570. console.warn("BJS - " + formattedMessage);
  9571. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9572. Tools._AddLogEntry(entry);
  9573. };
  9574. Tools._ErrorDisabled = function (message) {
  9575. // nothing to do
  9576. };
  9577. Tools._ErrorEnabled = function (message) {
  9578. Tools.errorsCount++;
  9579. var formattedMessage = Tools._FormatMessage(message);
  9580. console.error("BJS - " + formattedMessage);
  9581. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9582. Tools._AddLogEntry(entry);
  9583. };
  9584. Object.defineProperty(Tools, "LogCache", {
  9585. get: function () {
  9586. return Tools._LogCache;
  9587. },
  9588. enumerable: true,
  9589. configurable: true
  9590. });
  9591. Tools.ClearLogCache = function () {
  9592. Tools._LogCache = "";
  9593. Tools.errorsCount = 0;
  9594. };
  9595. Object.defineProperty(Tools, "LogLevels", {
  9596. set: function (level) {
  9597. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9598. Tools.Log = Tools._LogEnabled;
  9599. }
  9600. else {
  9601. Tools.Log = Tools._LogDisabled;
  9602. }
  9603. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9604. Tools.Warn = Tools._WarnEnabled;
  9605. }
  9606. else {
  9607. Tools.Warn = Tools._WarnDisabled;
  9608. }
  9609. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9610. Tools.Error = Tools._ErrorEnabled;
  9611. }
  9612. else {
  9613. Tools.Error = Tools._ErrorDisabled;
  9614. }
  9615. },
  9616. enumerable: true,
  9617. configurable: true
  9618. });
  9619. Tools.IsWindowObjectExist = function () {
  9620. return (typeof window) !== "undefined";
  9621. };
  9622. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9623. get: function () {
  9624. return Tools._PerformanceNoneLogLevel;
  9625. },
  9626. enumerable: true,
  9627. configurable: true
  9628. });
  9629. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9630. get: function () {
  9631. return Tools._PerformanceUserMarkLogLevel;
  9632. },
  9633. enumerable: true,
  9634. configurable: true
  9635. });
  9636. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9637. get: function () {
  9638. return Tools._PerformanceConsoleLogLevel;
  9639. },
  9640. enumerable: true,
  9641. configurable: true
  9642. });
  9643. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9644. set: function (level) {
  9645. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9646. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9647. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9648. return;
  9649. }
  9650. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9651. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9652. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9653. return;
  9654. }
  9655. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9656. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9657. },
  9658. enumerable: true,
  9659. configurable: true
  9660. });
  9661. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9662. };
  9663. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9664. };
  9665. Tools._StartUserMark = function (counterName, condition) {
  9666. if (condition === void 0) { condition = true; }
  9667. if (!Tools._performance) {
  9668. if (!Tools.IsWindowObjectExist()) {
  9669. return;
  9670. }
  9671. Tools._performance = window.performance;
  9672. }
  9673. if (!condition || !Tools._performance.mark) {
  9674. return;
  9675. }
  9676. Tools._performance.mark(counterName + "-Begin");
  9677. };
  9678. Tools._EndUserMark = function (counterName, condition) {
  9679. if (condition === void 0) { condition = true; }
  9680. if (!condition || !Tools._performance.mark) {
  9681. return;
  9682. }
  9683. Tools._performance.mark(counterName + "-End");
  9684. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9685. };
  9686. Tools._StartPerformanceConsole = function (counterName, condition) {
  9687. if (condition === void 0) { condition = true; }
  9688. if (!condition) {
  9689. return;
  9690. }
  9691. Tools._StartUserMark(counterName, condition);
  9692. if (console.time) {
  9693. console.time(counterName);
  9694. }
  9695. };
  9696. Tools._EndPerformanceConsole = function (counterName, condition) {
  9697. if (condition === void 0) { condition = true; }
  9698. if (!condition) {
  9699. return;
  9700. }
  9701. Tools._EndUserMark(counterName, condition);
  9702. if (console.time) {
  9703. console.timeEnd(counterName);
  9704. }
  9705. };
  9706. Object.defineProperty(Tools, "Now", {
  9707. get: function () {
  9708. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9709. return window.performance.now();
  9710. }
  9711. return Date.now();
  9712. },
  9713. enumerable: true,
  9714. configurable: true
  9715. });
  9716. /**
  9717. * This method will return the name of the class used to create the instance of the given object.
  9718. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9719. * @param object the object to get the class name from
  9720. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9721. */
  9722. Tools.GetClassName = function (object, isType) {
  9723. if (isType === void 0) { isType = false; }
  9724. var name = null;
  9725. if (!isType && object.getClassName) {
  9726. name = object.getClassName();
  9727. }
  9728. else {
  9729. if (object instanceof Object) {
  9730. var classObj = isType ? object : Object.getPrototypeOf(object);
  9731. name = classObj.constructor["__bjsclassName__"];
  9732. }
  9733. if (!name) {
  9734. name = typeof object;
  9735. }
  9736. }
  9737. return name;
  9738. };
  9739. Tools.First = function (array, predicate) {
  9740. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9741. var el = array_1[_i];
  9742. if (predicate(el)) {
  9743. return el;
  9744. }
  9745. }
  9746. return null;
  9747. };
  9748. /**
  9749. * This method will return the name of the full name of the class, including its owning module (if any).
  9750. * 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).
  9751. * @param object the object to get the class name from
  9752. * @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.
  9753. */
  9754. Tools.getFullClassName = function (object, isType) {
  9755. if (isType === void 0) { isType = false; }
  9756. var className = null;
  9757. var moduleName = null;
  9758. if (!isType && object.getClassName) {
  9759. className = object.getClassName();
  9760. }
  9761. else {
  9762. if (object instanceof Object) {
  9763. var classObj = isType ? object : Object.getPrototypeOf(object);
  9764. className = classObj.constructor["__bjsclassName__"];
  9765. moduleName = classObj.constructor["__bjsmoduleName__"];
  9766. }
  9767. if (!className) {
  9768. className = typeof object;
  9769. }
  9770. }
  9771. if (!className) {
  9772. return null;
  9773. }
  9774. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9775. };
  9776. /**
  9777. * 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.
  9778. * @param array
  9779. */
  9780. Tools.arrayOrStringFeeder = function (array) {
  9781. return function (index) {
  9782. if (index >= array.length) {
  9783. return null;
  9784. }
  9785. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9786. if (val && val.getHashCode) {
  9787. val = val.getHashCode();
  9788. }
  9789. if (typeof val === "string") {
  9790. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9791. }
  9792. return val;
  9793. };
  9794. };
  9795. /**
  9796. * Compute the hashCode of a stream of number
  9797. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9798. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9799. * @return the hash code computed
  9800. */
  9801. Tools.hashCodeFromStream = function (feeder) {
  9802. // Based from here: http://stackoverflow.com/a/7616484/802124
  9803. var hash = 0;
  9804. var index = 0;
  9805. var chr = feeder(index++);
  9806. while (chr != null) {
  9807. hash = ((hash << 5) - hash) + chr;
  9808. hash |= 0; // Convert to 32bit integer
  9809. chr = feeder(index++);
  9810. }
  9811. return hash;
  9812. };
  9813. /**
  9814. * Returns a promise that resolves after the given amount of time.
  9815. * @param delay Number of milliseconds to delay
  9816. * @returns Promise that resolves after the given amount of time
  9817. */
  9818. Tools.DelayAsync = function (delay) {
  9819. return new Promise(function (resolve) {
  9820. setTimeout(function () {
  9821. resolve();
  9822. }, delay);
  9823. });
  9824. };
  9825. Tools.BaseUrl = "";
  9826. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9827. /**
  9828. * Default behaviour for cors in the application.
  9829. * It can be a string if the expected behavior is identical in the entire app.
  9830. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9831. */
  9832. Tools.CorsBehavior = "anonymous";
  9833. Tools.UseFallbackTexture = true;
  9834. /**
  9835. * Use this object to register external classes like custom textures or material
  9836. * to allow the laoders to instantiate them
  9837. */
  9838. Tools.RegisteredExternalClasses = {};
  9839. // Used in case of a texture loading problem
  9840. 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";
  9841. Tools._tmpFloatArray = new Float32Array(1);
  9842. Tools.PreprocessUrl = function (url) {
  9843. return url;
  9844. };
  9845. // Logs
  9846. Tools._NoneLogLevel = 0;
  9847. Tools._MessageLogLevel = 1;
  9848. Tools._WarningLogLevel = 2;
  9849. Tools._ErrorLogLevel = 4;
  9850. Tools._LogCache = "";
  9851. Tools.errorsCount = 0;
  9852. Tools.Log = Tools._LogEnabled;
  9853. Tools.Warn = Tools._WarnEnabled;
  9854. Tools.Error = Tools._ErrorEnabled;
  9855. // Performances
  9856. Tools._PerformanceNoneLogLevel = 0;
  9857. Tools._PerformanceUserMarkLogLevel = 1;
  9858. Tools._PerformanceConsoleLogLevel = 2;
  9859. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9860. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9861. return Tools;
  9862. }());
  9863. BABYLON.Tools = Tools;
  9864. /**
  9865. * This class is used to track a performance counter which is number based.
  9866. * The user has access to many properties which give statistics of different nature
  9867. *
  9868. * The implementer can track two kinds of Performance Counter: time and count
  9869. * 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.
  9870. * 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.
  9871. */
  9872. var PerfCounter = /** @class */ (function () {
  9873. function PerfCounter() {
  9874. this._startMonitoringTime = 0;
  9875. this._min = 0;
  9876. this._max = 0;
  9877. this._average = 0;
  9878. this._lastSecAverage = 0;
  9879. this._current = 0;
  9880. this._totalValueCount = 0;
  9881. this._totalAccumulated = 0;
  9882. this._lastSecAccumulated = 0;
  9883. this._lastSecTime = 0;
  9884. this._lastSecValueCount = 0;
  9885. }
  9886. Object.defineProperty(PerfCounter.prototype, "min", {
  9887. /**
  9888. * Returns the smallest value ever
  9889. */
  9890. get: function () {
  9891. return this._min;
  9892. },
  9893. enumerable: true,
  9894. configurable: true
  9895. });
  9896. Object.defineProperty(PerfCounter.prototype, "max", {
  9897. /**
  9898. * Returns the biggest value ever
  9899. */
  9900. get: function () {
  9901. return this._max;
  9902. },
  9903. enumerable: true,
  9904. configurable: true
  9905. });
  9906. Object.defineProperty(PerfCounter.prototype, "average", {
  9907. /**
  9908. * Returns the average value since the performance counter is running
  9909. */
  9910. get: function () {
  9911. return this._average;
  9912. },
  9913. enumerable: true,
  9914. configurable: true
  9915. });
  9916. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9917. /**
  9918. * Returns the average value of the last second the counter was monitored
  9919. */
  9920. get: function () {
  9921. return this._lastSecAverage;
  9922. },
  9923. enumerable: true,
  9924. configurable: true
  9925. });
  9926. Object.defineProperty(PerfCounter.prototype, "current", {
  9927. /**
  9928. * Returns the current value
  9929. */
  9930. get: function () {
  9931. return this._current;
  9932. },
  9933. enumerable: true,
  9934. configurable: true
  9935. });
  9936. Object.defineProperty(PerfCounter.prototype, "total", {
  9937. get: function () {
  9938. return this._totalAccumulated;
  9939. },
  9940. enumerable: true,
  9941. configurable: true
  9942. });
  9943. Object.defineProperty(PerfCounter.prototype, "count", {
  9944. get: function () {
  9945. return this._totalValueCount;
  9946. },
  9947. enumerable: true,
  9948. configurable: true
  9949. });
  9950. /**
  9951. * Call this method to start monitoring a new frame.
  9952. * 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.
  9953. */
  9954. PerfCounter.prototype.fetchNewFrame = function () {
  9955. this._totalValueCount++;
  9956. this._current = 0;
  9957. this._lastSecValueCount++;
  9958. };
  9959. /**
  9960. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9961. * @param newCount the count value to add to the monitored count
  9962. * @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.
  9963. */
  9964. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9965. if (!PerfCounter.Enabled) {
  9966. return;
  9967. }
  9968. this._current += newCount;
  9969. if (fetchResult) {
  9970. this._fetchResult();
  9971. }
  9972. };
  9973. /**
  9974. * Start monitoring this performance counter
  9975. */
  9976. PerfCounter.prototype.beginMonitoring = function () {
  9977. if (!PerfCounter.Enabled) {
  9978. return;
  9979. }
  9980. this._startMonitoringTime = Tools.Now;
  9981. };
  9982. /**
  9983. * Compute the time lapsed since the previous beginMonitoring() call.
  9984. * @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
  9985. */
  9986. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9987. if (newFrame === void 0) { newFrame = true; }
  9988. if (!PerfCounter.Enabled) {
  9989. return;
  9990. }
  9991. if (newFrame) {
  9992. this.fetchNewFrame();
  9993. }
  9994. var currentTime = Tools.Now;
  9995. this._current = currentTime - this._startMonitoringTime;
  9996. if (newFrame) {
  9997. this._fetchResult();
  9998. }
  9999. };
  10000. PerfCounter.prototype._fetchResult = function () {
  10001. this._totalAccumulated += this._current;
  10002. this._lastSecAccumulated += this._current;
  10003. // Min/Max update
  10004. this._min = Math.min(this._min, this._current);
  10005. this._max = Math.max(this._max, this._current);
  10006. this._average = this._totalAccumulated / this._totalValueCount;
  10007. // Reset last sec?
  10008. var now = Tools.Now;
  10009. if ((now - this._lastSecTime) > 1000) {
  10010. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10011. this._lastSecTime = now;
  10012. this._lastSecAccumulated = 0;
  10013. this._lastSecValueCount = 0;
  10014. }
  10015. };
  10016. PerfCounter.Enabled = true;
  10017. return PerfCounter;
  10018. }());
  10019. BABYLON.PerfCounter = PerfCounter;
  10020. /**
  10021. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10022. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10023. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10024. * @param name The name of the class, case should be preserved
  10025. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10026. */
  10027. function className(name, module) {
  10028. return function (target) {
  10029. target["__bjsclassName__"] = name;
  10030. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10031. };
  10032. }
  10033. BABYLON.className = className;
  10034. /**
  10035. * An implementation of a loop for asynchronous functions.
  10036. */
  10037. var AsyncLoop = /** @class */ (function () {
  10038. /**
  10039. * Constroctor.
  10040. * @param iterations the number of iterations.
  10041. * @param _fn the function to run each iteration
  10042. * @param _successCallback the callback that will be called upon succesful execution
  10043. * @param offset starting offset.
  10044. */
  10045. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10046. if (offset === void 0) { offset = 0; }
  10047. this.iterations = iterations;
  10048. this._fn = _fn;
  10049. this._successCallback = _successCallback;
  10050. this.index = offset - 1;
  10051. this._done = false;
  10052. }
  10053. /**
  10054. * Execute the next iteration. Must be called after the last iteration was finished.
  10055. */
  10056. AsyncLoop.prototype.executeNext = function () {
  10057. if (!this._done) {
  10058. if (this.index + 1 < this.iterations) {
  10059. ++this.index;
  10060. this._fn(this);
  10061. }
  10062. else {
  10063. this.breakLoop();
  10064. }
  10065. }
  10066. };
  10067. /**
  10068. * Break the loop and run the success callback.
  10069. */
  10070. AsyncLoop.prototype.breakLoop = function () {
  10071. this._done = true;
  10072. this._successCallback();
  10073. };
  10074. /**
  10075. * Helper function
  10076. */
  10077. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10078. if (offset === void 0) { offset = 0; }
  10079. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10080. loop.executeNext();
  10081. return loop;
  10082. };
  10083. /**
  10084. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10085. * @param iterations total number of iterations
  10086. * @param syncedIterations number of synchronous iterations in each async iteration.
  10087. * @param fn the function to call each iteration.
  10088. * @param callback a success call back that will be called when iterating stops.
  10089. * @param breakFunction a break condition (optional)
  10090. * @param timeout timeout settings for the setTimeout function. default - 0.
  10091. * @constructor
  10092. */
  10093. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10094. if (timeout === void 0) { timeout = 0; }
  10095. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10096. if (breakFunction && breakFunction())
  10097. loop.breakLoop();
  10098. else {
  10099. setTimeout(function () {
  10100. for (var i = 0; i < syncedIterations; ++i) {
  10101. var iteration = (loop.index * syncedIterations) + i;
  10102. if (iteration >= iterations)
  10103. break;
  10104. fn(iteration);
  10105. if (breakFunction && breakFunction()) {
  10106. loop.breakLoop();
  10107. break;
  10108. }
  10109. }
  10110. loop.executeNext();
  10111. }, timeout);
  10112. }
  10113. }, callback);
  10114. };
  10115. return AsyncLoop;
  10116. }());
  10117. BABYLON.AsyncLoop = AsyncLoop;
  10118. })(BABYLON || (BABYLON = {}));
  10119. //# sourceMappingURL=babylon.tools.js.map
  10120. var BABYLON;
  10121. (function (BABYLON) {
  10122. var PromiseStates;
  10123. (function (PromiseStates) {
  10124. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10125. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10126. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10127. })(PromiseStates || (PromiseStates = {}));
  10128. var FulFillmentAgregator = /** @class */ (function () {
  10129. function FulFillmentAgregator() {
  10130. this.count = 0;
  10131. this.target = 0;
  10132. this.results = [];
  10133. }
  10134. return FulFillmentAgregator;
  10135. }());
  10136. var InternalPromise = /** @class */ (function () {
  10137. function InternalPromise(resolver) {
  10138. var _this = this;
  10139. this._state = PromiseStates.Pending;
  10140. this._children = new Array();
  10141. this._rejectWasConsumed = false;
  10142. if (!resolver) {
  10143. return;
  10144. }
  10145. try {
  10146. resolver(function (value) {
  10147. _this._resolve(value);
  10148. }, function (reason) {
  10149. _this._reject(reason);
  10150. });
  10151. }
  10152. catch (e) {
  10153. this._reject(e);
  10154. }
  10155. }
  10156. Object.defineProperty(InternalPromise.prototype, "_result", {
  10157. get: function () {
  10158. return this._resultValue;
  10159. },
  10160. set: function (value) {
  10161. this._resultValue = value;
  10162. if (this._parent && this._parent._result === undefined) {
  10163. this._parent._result = value;
  10164. }
  10165. },
  10166. enumerable: true,
  10167. configurable: true
  10168. });
  10169. InternalPromise.prototype.catch = function (onRejected) {
  10170. return this.then(undefined, onRejected);
  10171. };
  10172. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10173. var _this = this;
  10174. var newPromise = new InternalPromise();
  10175. newPromise._onFulfilled = onFulfilled;
  10176. newPromise._onRejected = onRejected;
  10177. // Composition
  10178. this._children.push(newPromise);
  10179. newPromise._parent = this;
  10180. if (this._state !== PromiseStates.Pending) {
  10181. BABYLON.Tools.SetImmediate(function () {
  10182. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10183. var returnedValue = newPromise._resolve(_this._result);
  10184. if (returnedValue !== undefined && returnedValue !== null) {
  10185. if (returnedValue._state !== undefined) {
  10186. var returnedPromise = returnedValue;
  10187. newPromise._children.push(returnedPromise);
  10188. returnedPromise._parent = newPromise;
  10189. newPromise = returnedPromise;
  10190. }
  10191. else {
  10192. newPromise._result = returnedValue;
  10193. }
  10194. }
  10195. }
  10196. else {
  10197. newPromise._reject(_this._reason);
  10198. }
  10199. });
  10200. }
  10201. return newPromise;
  10202. };
  10203. InternalPromise.prototype._moveChildren = function (children) {
  10204. var _this = this;
  10205. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10206. this._children.forEach(function (child) {
  10207. child._parent = _this;
  10208. });
  10209. if (this._state === PromiseStates.Fulfilled) {
  10210. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10211. var child = _b[_i];
  10212. child._resolve(this._result);
  10213. }
  10214. }
  10215. else if (this._state === PromiseStates.Rejected) {
  10216. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10217. var child = _d[_c];
  10218. child._reject(this._reason);
  10219. }
  10220. }
  10221. var _a;
  10222. };
  10223. InternalPromise.prototype._resolve = function (value) {
  10224. try {
  10225. this._state = PromiseStates.Fulfilled;
  10226. var returnedValue = null;
  10227. if (this._onFulfilled) {
  10228. returnedValue = this._onFulfilled(value);
  10229. }
  10230. if (returnedValue !== undefined && returnedValue !== null) {
  10231. if (returnedValue._state !== undefined) {
  10232. // Transmit children
  10233. var returnedPromise = returnedValue;
  10234. returnedPromise._parent = this;
  10235. returnedPromise._moveChildren(this._children);
  10236. value = returnedPromise._result;
  10237. }
  10238. else {
  10239. value = returnedValue;
  10240. }
  10241. }
  10242. this._result = value;
  10243. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10244. var child = _a[_i];
  10245. child._resolve(value);
  10246. }
  10247. this._children.length = 0;
  10248. delete this._onFulfilled;
  10249. delete this._onRejected;
  10250. }
  10251. catch (e) {
  10252. this._reject(e, true);
  10253. }
  10254. };
  10255. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10256. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10257. this._state = PromiseStates.Rejected;
  10258. this._reason = reason;
  10259. if (this._onRejected && !onLocalThrow) {
  10260. try {
  10261. this._onRejected(reason);
  10262. this._rejectWasConsumed = true;
  10263. }
  10264. catch (e) {
  10265. reason = e;
  10266. }
  10267. }
  10268. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10269. var child = _a[_i];
  10270. if (this._rejectWasConsumed) {
  10271. child._resolve(null);
  10272. }
  10273. else {
  10274. child._reject(reason);
  10275. }
  10276. }
  10277. this._children.length = 0;
  10278. delete this._onFulfilled;
  10279. delete this._onRejected;
  10280. };
  10281. InternalPromise.resolve = function (value) {
  10282. var newPromise = new InternalPromise();
  10283. newPromise._resolve(value);
  10284. return newPromise;
  10285. };
  10286. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10287. promise.then(function (value) {
  10288. agregator.results[index] = value;
  10289. agregator.count++;
  10290. if (agregator.count === agregator.target) {
  10291. agregator.rootPromise._resolve(agregator.results);
  10292. }
  10293. return null;
  10294. }, function (reason) {
  10295. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10296. agregator.rootPromise._reject(reason);
  10297. }
  10298. });
  10299. };
  10300. InternalPromise.all = function (promises) {
  10301. var newPromise = new InternalPromise();
  10302. var agregator = new FulFillmentAgregator();
  10303. agregator.target = promises.length;
  10304. agregator.rootPromise = newPromise;
  10305. if (promises.length) {
  10306. for (var index = 0; index < promises.length; index++) {
  10307. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10308. }
  10309. }
  10310. else {
  10311. newPromise._resolve([]);
  10312. }
  10313. return newPromise;
  10314. };
  10315. InternalPromise.race = function (promises) {
  10316. var newPromise = new InternalPromise();
  10317. if (promises.length) {
  10318. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10319. var promise = promises_1[_i];
  10320. promise.then(function (value) {
  10321. if (newPromise) {
  10322. newPromise._resolve(value);
  10323. newPromise = null;
  10324. }
  10325. return null;
  10326. }, function (reason) {
  10327. if (newPromise) {
  10328. newPromise._reject(reason);
  10329. newPromise = null;
  10330. }
  10331. });
  10332. }
  10333. }
  10334. return newPromise;
  10335. };
  10336. return InternalPromise;
  10337. }());
  10338. /**
  10339. * Helper class that provides a small promise polyfill
  10340. */
  10341. var PromisePolyfill = /** @class */ (function () {
  10342. function PromisePolyfill() {
  10343. }
  10344. /**
  10345. * Static function used to check if the polyfill is required
  10346. * If this is the case then the function will inject the polyfill to window.Promise
  10347. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10348. */
  10349. PromisePolyfill.Apply = function (force) {
  10350. if (force === void 0) { force = false; }
  10351. if (force || typeof Promise === 'undefined') {
  10352. var root = window;
  10353. root.Promise = InternalPromise;
  10354. }
  10355. };
  10356. return PromisePolyfill;
  10357. }());
  10358. BABYLON.PromisePolyfill = PromisePolyfill;
  10359. })(BABYLON || (BABYLON = {}));
  10360. //# sourceMappingURL=babylon.promise.js.map
  10361. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10362. var BABYLON;
  10363. (function (BABYLON) {
  10364. /**
  10365. * Helper class to push actions to a pool of workers.
  10366. */
  10367. var WorkerPool = /** @class */ (function () {
  10368. /**
  10369. * Constructor
  10370. * @param workers Array of workers to use for actions
  10371. */
  10372. function WorkerPool(workers) {
  10373. this._pendingActions = new Array();
  10374. this._workerInfos = workers.map(function (worker) { return ({
  10375. worker: worker,
  10376. active: false
  10377. }); });
  10378. }
  10379. /**
  10380. * Terminates all workers and clears any pending actions.
  10381. */
  10382. WorkerPool.prototype.dispose = function () {
  10383. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10384. var workerInfo = _a[_i];
  10385. workerInfo.worker.terminate();
  10386. }
  10387. delete this._workerInfos;
  10388. delete this._pendingActions;
  10389. };
  10390. /**
  10391. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10392. * pended until a worker has completed its action.
  10393. * @param action The action to perform. Call onComplete when the action is complete.
  10394. */
  10395. WorkerPool.prototype.push = function (action) {
  10396. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10397. var workerInfo = _a[_i];
  10398. if (!workerInfo.active) {
  10399. this._execute(workerInfo, action);
  10400. return;
  10401. }
  10402. }
  10403. this._pendingActions.push(action);
  10404. };
  10405. WorkerPool.prototype._execute = function (workerInfo, action) {
  10406. var _this = this;
  10407. workerInfo.active = true;
  10408. action(workerInfo.worker, function () {
  10409. workerInfo.active = false;
  10410. var nextAction = _this._pendingActions.shift();
  10411. if (nextAction) {
  10412. _this._execute(workerInfo, nextAction);
  10413. }
  10414. });
  10415. };
  10416. return WorkerPool;
  10417. }());
  10418. BABYLON.WorkerPool = WorkerPool;
  10419. })(BABYLON || (BABYLON = {}));
  10420. //# sourceMappingURL=babylon.workerPool.js.map
  10421. var BABYLON;
  10422. (function (BABYLON) {
  10423. /**
  10424. * @hidden
  10425. **/
  10426. var _AlphaState = /** @class */ (function () {
  10427. /**
  10428. * Initializes the state.
  10429. */
  10430. function _AlphaState() {
  10431. this._isAlphaBlendDirty = false;
  10432. this._isBlendFunctionParametersDirty = false;
  10433. this._isBlendEquationParametersDirty = false;
  10434. this._isBlendConstantsDirty = false;
  10435. this._alphaBlend = false;
  10436. this._blendFunctionParameters = new Array(4);
  10437. this._blendEquationParameters = new Array(2);
  10438. this._blendConstants = new Array(4);
  10439. this.reset();
  10440. }
  10441. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10442. get: function () {
  10443. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10444. },
  10445. enumerable: true,
  10446. configurable: true
  10447. });
  10448. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10449. get: function () {
  10450. return this._alphaBlend;
  10451. },
  10452. set: function (value) {
  10453. if (this._alphaBlend === value) {
  10454. return;
  10455. }
  10456. this._alphaBlend = value;
  10457. this._isAlphaBlendDirty = true;
  10458. },
  10459. enumerable: true,
  10460. configurable: true
  10461. });
  10462. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10463. if (this._blendConstants[0] === r &&
  10464. this._blendConstants[1] === g &&
  10465. this._blendConstants[2] === b &&
  10466. this._blendConstants[3] === a) {
  10467. return;
  10468. }
  10469. this._blendConstants[0] = r;
  10470. this._blendConstants[1] = g;
  10471. this._blendConstants[2] = b;
  10472. this._blendConstants[3] = a;
  10473. this._isBlendConstantsDirty = true;
  10474. };
  10475. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10476. if (this._blendFunctionParameters[0] === value0 &&
  10477. this._blendFunctionParameters[1] === value1 &&
  10478. this._blendFunctionParameters[2] === value2 &&
  10479. this._blendFunctionParameters[3] === value3) {
  10480. return;
  10481. }
  10482. this._blendFunctionParameters[0] = value0;
  10483. this._blendFunctionParameters[1] = value1;
  10484. this._blendFunctionParameters[2] = value2;
  10485. this._blendFunctionParameters[3] = value3;
  10486. this._isBlendFunctionParametersDirty = true;
  10487. };
  10488. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10489. if (this._blendEquationParameters[0] === rgb &&
  10490. this._blendEquationParameters[1] === alpha) {
  10491. return;
  10492. }
  10493. this._blendEquationParameters[0] = rgb;
  10494. this._blendEquationParameters[1] = alpha;
  10495. this._isBlendEquationParametersDirty = true;
  10496. };
  10497. _AlphaState.prototype.reset = function () {
  10498. this._alphaBlend = false;
  10499. this._blendFunctionParameters[0] = null;
  10500. this._blendFunctionParameters[1] = null;
  10501. this._blendFunctionParameters[2] = null;
  10502. this._blendFunctionParameters[3] = null;
  10503. this._blendEquationParameters[0] = null;
  10504. this._blendEquationParameters[1] = null;
  10505. this._blendConstants[0] = null;
  10506. this._blendConstants[1] = null;
  10507. this._blendConstants[2] = null;
  10508. this._blendConstants[3] = null;
  10509. this._isAlphaBlendDirty = true;
  10510. this._isBlendFunctionParametersDirty = false;
  10511. this._isBlendEquationParametersDirty = false;
  10512. this._isBlendConstantsDirty = false;
  10513. };
  10514. _AlphaState.prototype.apply = function (gl) {
  10515. if (!this.isDirty) {
  10516. return;
  10517. }
  10518. // Alpha blend
  10519. if (this._isAlphaBlendDirty) {
  10520. if (this._alphaBlend) {
  10521. gl.enable(gl.BLEND);
  10522. }
  10523. else {
  10524. gl.disable(gl.BLEND);
  10525. }
  10526. this._isAlphaBlendDirty = false;
  10527. }
  10528. // Alpha function
  10529. if (this._isBlendFunctionParametersDirty) {
  10530. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10531. this._isBlendFunctionParametersDirty = false;
  10532. }
  10533. // Alpha equation
  10534. if (this._isBlendEquationParametersDirty) {
  10535. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10536. this._isBlendEquationParametersDirty = false;
  10537. }
  10538. // Constants
  10539. if (this._isBlendConstantsDirty) {
  10540. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10541. this._isBlendConstantsDirty = false;
  10542. }
  10543. };
  10544. return _AlphaState;
  10545. }());
  10546. BABYLON._AlphaState = _AlphaState;
  10547. })(BABYLON || (BABYLON = {}));
  10548. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10549. var BABYLON;
  10550. (function (BABYLON) {
  10551. /**
  10552. * @hidden
  10553. **/
  10554. var _DepthCullingState = /** @class */ (function () {
  10555. /**
  10556. * Initializes the state.
  10557. */
  10558. function _DepthCullingState() {
  10559. this._isDepthTestDirty = false;
  10560. this._isDepthMaskDirty = false;
  10561. this._isDepthFuncDirty = false;
  10562. this._isCullFaceDirty = false;
  10563. this._isCullDirty = false;
  10564. this._isZOffsetDirty = false;
  10565. this._isFrontFaceDirty = false;
  10566. this.reset();
  10567. }
  10568. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10569. get: function () {
  10570. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10571. },
  10572. enumerable: true,
  10573. configurable: true
  10574. });
  10575. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10576. get: function () {
  10577. return this._zOffset;
  10578. },
  10579. set: function (value) {
  10580. if (this._zOffset === value) {
  10581. return;
  10582. }
  10583. this._zOffset = value;
  10584. this._isZOffsetDirty = true;
  10585. },
  10586. enumerable: true,
  10587. configurable: true
  10588. });
  10589. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10590. get: function () {
  10591. return this._cullFace;
  10592. },
  10593. set: function (value) {
  10594. if (this._cullFace === value) {
  10595. return;
  10596. }
  10597. this._cullFace = value;
  10598. this._isCullFaceDirty = true;
  10599. },
  10600. enumerable: true,
  10601. configurable: true
  10602. });
  10603. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10604. get: function () {
  10605. return this._cull;
  10606. },
  10607. set: function (value) {
  10608. if (this._cull === value) {
  10609. return;
  10610. }
  10611. this._cull = value;
  10612. this._isCullDirty = true;
  10613. },
  10614. enumerable: true,
  10615. configurable: true
  10616. });
  10617. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10618. get: function () {
  10619. return this._depthFunc;
  10620. },
  10621. set: function (value) {
  10622. if (this._depthFunc === value) {
  10623. return;
  10624. }
  10625. this._depthFunc = value;
  10626. this._isDepthFuncDirty = true;
  10627. },
  10628. enumerable: true,
  10629. configurable: true
  10630. });
  10631. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10632. get: function () {
  10633. return this._depthMask;
  10634. },
  10635. set: function (value) {
  10636. if (this._depthMask === value) {
  10637. return;
  10638. }
  10639. this._depthMask = value;
  10640. this._isDepthMaskDirty = true;
  10641. },
  10642. enumerable: true,
  10643. configurable: true
  10644. });
  10645. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10646. get: function () {
  10647. return this._depthTest;
  10648. },
  10649. set: function (value) {
  10650. if (this._depthTest === value) {
  10651. return;
  10652. }
  10653. this._depthTest = value;
  10654. this._isDepthTestDirty = true;
  10655. },
  10656. enumerable: true,
  10657. configurable: true
  10658. });
  10659. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10660. get: function () {
  10661. return this._frontFace;
  10662. },
  10663. set: function (value) {
  10664. if (this._frontFace === value) {
  10665. return;
  10666. }
  10667. this._frontFace = value;
  10668. this._isFrontFaceDirty = true;
  10669. },
  10670. enumerable: true,
  10671. configurable: true
  10672. });
  10673. _DepthCullingState.prototype.reset = function () {
  10674. this._depthMask = true;
  10675. this._depthTest = true;
  10676. this._depthFunc = null;
  10677. this._cullFace = null;
  10678. this._cull = null;
  10679. this._zOffset = 0;
  10680. this._frontFace = null;
  10681. this._isDepthTestDirty = true;
  10682. this._isDepthMaskDirty = true;
  10683. this._isDepthFuncDirty = false;
  10684. this._isCullFaceDirty = false;
  10685. this._isCullDirty = false;
  10686. this._isZOffsetDirty = false;
  10687. this._isFrontFaceDirty = false;
  10688. };
  10689. _DepthCullingState.prototype.apply = function (gl) {
  10690. if (!this.isDirty) {
  10691. return;
  10692. }
  10693. // Cull
  10694. if (this._isCullDirty) {
  10695. if (this.cull) {
  10696. gl.enable(gl.CULL_FACE);
  10697. }
  10698. else {
  10699. gl.disable(gl.CULL_FACE);
  10700. }
  10701. this._isCullDirty = false;
  10702. }
  10703. // Cull face
  10704. if (this._isCullFaceDirty) {
  10705. gl.cullFace(this.cullFace);
  10706. this._isCullFaceDirty = false;
  10707. }
  10708. // Depth mask
  10709. if (this._isDepthMaskDirty) {
  10710. gl.depthMask(this.depthMask);
  10711. this._isDepthMaskDirty = false;
  10712. }
  10713. // Depth test
  10714. if (this._isDepthTestDirty) {
  10715. if (this.depthTest) {
  10716. gl.enable(gl.DEPTH_TEST);
  10717. }
  10718. else {
  10719. gl.disable(gl.DEPTH_TEST);
  10720. }
  10721. this._isDepthTestDirty = false;
  10722. }
  10723. // Depth func
  10724. if (this._isDepthFuncDirty) {
  10725. gl.depthFunc(this.depthFunc);
  10726. this._isDepthFuncDirty = false;
  10727. }
  10728. // zOffset
  10729. if (this._isZOffsetDirty) {
  10730. if (this.zOffset) {
  10731. gl.enable(gl.POLYGON_OFFSET_FILL);
  10732. gl.polygonOffset(this.zOffset, 0);
  10733. }
  10734. else {
  10735. gl.disable(gl.POLYGON_OFFSET_FILL);
  10736. }
  10737. this._isZOffsetDirty = false;
  10738. }
  10739. // Front face
  10740. if (this._isFrontFaceDirty) {
  10741. gl.frontFace(this.frontFace);
  10742. this._isFrontFaceDirty = false;
  10743. }
  10744. };
  10745. return _DepthCullingState;
  10746. }());
  10747. BABYLON._DepthCullingState = _DepthCullingState;
  10748. })(BABYLON || (BABYLON = {}));
  10749. //# sourceMappingURL=babylon.depthCullingState.js.map
  10750. var BABYLON;
  10751. (function (BABYLON) {
  10752. /**
  10753. * @hidden
  10754. **/
  10755. var _StencilState = /** @class */ (function () {
  10756. function _StencilState() {
  10757. this._isStencilTestDirty = false;
  10758. this._isStencilMaskDirty = false;
  10759. this._isStencilFuncDirty = false;
  10760. this._isStencilOpDirty = false;
  10761. this.reset();
  10762. }
  10763. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10764. get: function () {
  10765. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10766. },
  10767. enumerable: true,
  10768. configurable: true
  10769. });
  10770. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10771. get: function () {
  10772. return this._stencilFunc;
  10773. },
  10774. set: function (value) {
  10775. if (this._stencilFunc === value) {
  10776. return;
  10777. }
  10778. this._stencilFunc = value;
  10779. this._isStencilFuncDirty = true;
  10780. },
  10781. enumerable: true,
  10782. configurable: true
  10783. });
  10784. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10785. get: function () {
  10786. return this._stencilFuncRef;
  10787. },
  10788. set: function (value) {
  10789. if (this._stencilFuncRef === value) {
  10790. return;
  10791. }
  10792. this._stencilFuncRef = value;
  10793. this._isStencilFuncDirty = true;
  10794. },
  10795. enumerable: true,
  10796. configurable: true
  10797. });
  10798. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10799. get: function () {
  10800. return this._stencilFuncMask;
  10801. },
  10802. set: function (value) {
  10803. if (this._stencilFuncMask === value) {
  10804. return;
  10805. }
  10806. this._stencilFuncMask = value;
  10807. this._isStencilFuncDirty = true;
  10808. },
  10809. enumerable: true,
  10810. configurable: true
  10811. });
  10812. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10813. get: function () {
  10814. return this._stencilOpStencilFail;
  10815. },
  10816. set: function (value) {
  10817. if (this._stencilOpStencilFail === value) {
  10818. return;
  10819. }
  10820. this._stencilOpStencilFail = value;
  10821. this._isStencilOpDirty = true;
  10822. },
  10823. enumerable: true,
  10824. configurable: true
  10825. });
  10826. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10827. get: function () {
  10828. return this._stencilOpDepthFail;
  10829. },
  10830. set: function (value) {
  10831. if (this._stencilOpDepthFail === value) {
  10832. return;
  10833. }
  10834. this._stencilOpDepthFail = value;
  10835. this._isStencilOpDirty = true;
  10836. },
  10837. enumerable: true,
  10838. configurable: true
  10839. });
  10840. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10841. get: function () {
  10842. return this._stencilOpStencilDepthPass;
  10843. },
  10844. set: function (value) {
  10845. if (this._stencilOpStencilDepthPass === value) {
  10846. return;
  10847. }
  10848. this._stencilOpStencilDepthPass = value;
  10849. this._isStencilOpDirty = true;
  10850. },
  10851. enumerable: true,
  10852. configurable: true
  10853. });
  10854. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10855. get: function () {
  10856. return this._stencilMask;
  10857. },
  10858. set: function (value) {
  10859. if (this._stencilMask === value) {
  10860. return;
  10861. }
  10862. this._stencilMask = value;
  10863. this._isStencilMaskDirty = true;
  10864. },
  10865. enumerable: true,
  10866. configurable: true
  10867. });
  10868. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10869. get: function () {
  10870. return this._stencilTest;
  10871. },
  10872. set: function (value) {
  10873. if (this._stencilTest === value) {
  10874. return;
  10875. }
  10876. this._stencilTest = value;
  10877. this._isStencilTestDirty = true;
  10878. },
  10879. enumerable: true,
  10880. configurable: true
  10881. });
  10882. _StencilState.prototype.reset = function () {
  10883. this._stencilTest = false;
  10884. this._stencilMask = 0xFF;
  10885. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10886. this._stencilFuncRef = 1;
  10887. this._stencilFuncMask = 0xFF;
  10888. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10889. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10890. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10891. this._isStencilTestDirty = true;
  10892. this._isStencilMaskDirty = true;
  10893. this._isStencilFuncDirty = true;
  10894. this._isStencilOpDirty = true;
  10895. };
  10896. _StencilState.prototype.apply = function (gl) {
  10897. if (!this.isDirty) {
  10898. return;
  10899. }
  10900. // Stencil test
  10901. if (this._isStencilTestDirty) {
  10902. if (this.stencilTest) {
  10903. gl.enable(gl.STENCIL_TEST);
  10904. }
  10905. else {
  10906. gl.disable(gl.STENCIL_TEST);
  10907. }
  10908. this._isStencilTestDirty = false;
  10909. }
  10910. // Stencil mask
  10911. if (this._isStencilMaskDirty) {
  10912. gl.stencilMask(this.stencilMask);
  10913. this._isStencilMaskDirty = false;
  10914. }
  10915. // Stencil func
  10916. if (this._isStencilFuncDirty) {
  10917. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10918. this._isStencilFuncDirty = false;
  10919. }
  10920. // Stencil op
  10921. if (this._isStencilOpDirty) {
  10922. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10923. this._isStencilOpDirty = false;
  10924. }
  10925. };
  10926. return _StencilState;
  10927. }());
  10928. BABYLON._StencilState = _StencilState;
  10929. })(BABYLON || (BABYLON = {}));
  10930. //# sourceMappingURL=babylon.stencilState.js.map
  10931. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10932. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10933. s = arguments[i];
  10934. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10935. t[p] = s[p];
  10936. }
  10937. return t;
  10938. };
  10939. var BABYLON;
  10940. (function (BABYLON) {
  10941. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10942. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10943. };
  10944. var compileRawShader = function (gl, source, type) {
  10945. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10946. gl.shaderSource(shader, source);
  10947. gl.compileShader(shader);
  10948. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10949. var log = gl.getShaderInfoLog(shader);
  10950. if (log) {
  10951. throw new Error(log);
  10952. }
  10953. }
  10954. if (!shader) {
  10955. throw new Error("Something went wrong while compile the shader.");
  10956. }
  10957. return shader;
  10958. };
  10959. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10960. var magFilter = gl.NEAREST;
  10961. var minFilter = gl.NEAREST;
  10962. switch (samplingMode) {
  10963. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10964. magFilter = gl.LINEAR;
  10965. if (generateMipMaps) {
  10966. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10967. }
  10968. else {
  10969. minFilter = gl.LINEAR;
  10970. }
  10971. break;
  10972. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10973. magFilter = gl.LINEAR;
  10974. if (generateMipMaps) {
  10975. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10976. }
  10977. else {
  10978. minFilter = gl.LINEAR;
  10979. }
  10980. break;
  10981. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10982. magFilter = gl.NEAREST;
  10983. if (generateMipMaps) {
  10984. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10985. }
  10986. else {
  10987. minFilter = gl.NEAREST;
  10988. }
  10989. break;
  10990. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10991. magFilter = gl.NEAREST;
  10992. if (generateMipMaps) {
  10993. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10994. }
  10995. else {
  10996. minFilter = gl.NEAREST;
  10997. }
  10998. break;
  10999. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11000. magFilter = gl.NEAREST;
  11001. if (generateMipMaps) {
  11002. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11003. }
  11004. else {
  11005. minFilter = gl.LINEAR;
  11006. }
  11007. break;
  11008. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11009. magFilter = gl.NEAREST;
  11010. if (generateMipMaps) {
  11011. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11012. }
  11013. else {
  11014. minFilter = gl.LINEAR;
  11015. }
  11016. break;
  11017. case BABYLON.Texture.NEAREST_LINEAR:
  11018. magFilter = gl.NEAREST;
  11019. minFilter = gl.LINEAR;
  11020. break;
  11021. case BABYLON.Texture.NEAREST_NEAREST:
  11022. magFilter = gl.NEAREST;
  11023. minFilter = gl.NEAREST;
  11024. break;
  11025. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11026. magFilter = gl.LINEAR;
  11027. if (generateMipMaps) {
  11028. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11029. }
  11030. else {
  11031. minFilter = gl.NEAREST;
  11032. }
  11033. break;
  11034. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11035. magFilter = gl.LINEAR;
  11036. if (generateMipMaps) {
  11037. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11038. }
  11039. else {
  11040. minFilter = gl.NEAREST;
  11041. }
  11042. break;
  11043. case BABYLON.Texture.LINEAR_LINEAR:
  11044. magFilter = gl.LINEAR;
  11045. minFilter = gl.LINEAR;
  11046. break;
  11047. case BABYLON.Texture.LINEAR_NEAREST:
  11048. magFilter = gl.LINEAR;
  11049. minFilter = gl.NEAREST;
  11050. break;
  11051. }
  11052. return {
  11053. min: minFilter,
  11054. mag: magFilter
  11055. };
  11056. };
  11057. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11058. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11059. var img;
  11060. var onload = function () {
  11061. loadedImages[index] = img;
  11062. loadedImages._internalCount++;
  11063. if (scene) {
  11064. scene._removePendingData(img);
  11065. }
  11066. if (loadedImages._internalCount === 6) {
  11067. onfinish(loadedImages);
  11068. }
  11069. };
  11070. var onerror = function (message, exception) {
  11071. if (scene) {
  11072. scene._removePendingData(img);
  11073. }
  11074. if (onErrorCallBack) {
  11075. onErrorCallBack(message, exception);
  11076. }
  11077. };
  11078. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11079. if (scene) {
  11080. scene._addPendingData(img);
  11081. }
  11082. };
  11083. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11084. if (onError === void 0) { onError = null; }
  11085. var loadedImages = [];
  11086. loadedImages._internalCount = 0;
  11087. for (var index = 0; index < 6; index++) {
  11088. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11089. }
  11090. };
  11091. var BufferPointer = /** @class */ (function () {
  11092. function BufferPointer() {
  11093. }
  11094. return BufferPointer;
  11095. }());
  11096. /**
  11097. * Interface for attribute information associated with buffer instanciation
  11098. */
  11099. var InstancingAttributeInfo = /** @class */ (function () {
  11100. function InstancingAttributeInfo() {
  11101. }
  11102. return InstancingAttributeInfo;
  11103. }());
  11104. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11105. /**
  11106. * Define options used to create a render target texture
  11107. */
  11108. var RenderTargetCreationOptions = /** @class */ (function () {
  11109. function RenderTargetCreationOptions() {
  11110. }
  11111. return RenderTargetCreationOptions;
  11112. }());
  11113. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11114. /**
  11115. * Define options used to create a depth texture
  11116. */
  11117. var DepthTextureCreationOptions = /** @class */ (function () {
  11118. function DepthTextureCreationOptions() {
  11119. }
  11120. return DepthTextureCreationOptions;
  11121. }());
  11122. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11123. /**
  11124. * Class used to describe the capabilities of the engine relatively to the current browser
  11125. */
  11126. var EngineCapabilities = /** @class */ (function () {
  11127. function EngineCapabilities() {
  11128. }
  11129. return EngineCapabilities;
  11130. }());
  11131. BABYLON.EngineCapabilities = EngineCapabilities;
  11132. /**
  11133. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11134. */
  11135. var Engine = /** @class */ (function () {
  11136. /**
  11137. * Creates a new engine
  11138. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11139. * @param antialias defines enable antialiasing (default: false)
  11140. * @param options defines further options to be sent to the getContext() function
  11141. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11142. */
  11143. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11144. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11145. var _this = this;
  11146. // Public members
  11147. /**
  11148. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11149. */
  11150. this.forcePOTTextures = false;
  11151. /**
  11152. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11153. */
  11154. this.isFullscreen = false;
  11155. /**
  11156. * Gets a boolean indicating if the pointer is currently locked
  11157. */
  11158. this.isPointerLock = false;
  11159. /**
  11160. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11161. */
  11162. this.cullBackFaces = true;
  11163. /**
  11164. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11165. */
  11166. this.renderEvenInBackground = true;
  11167. /**
  11168. * Gets or sets a boolean indicating that cache can be kept between frames
  11169. */
  11170. this.preventCacheWipeBetweenFrames = false;
  11171. /**
  11172. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11173. **/
  11174. this.enableOfflineSupport = false;
  11175. /**
  11176. * 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)
  11177. **/
  11178. this.disableManifestCheck = false;
  11179. /**
  11180. * Gets the list of created scenes
  11181. */
  11182. this.scenes = new Array();
  11183. /**
  11184. * Gets the list of created postprocesses
  11185. */
  11186. this.postProcesses = new Array();
  11187. // Observables
  11188. /**
  11189. * Observable event triggered each time the rendering canvas is resized
  11190. */
  11191. this.onResizeObservable = new BABYLON.Observable();
  11192. /**
  11193. * Observable event triggered each time the canvas loses focus
  11194. */
  11195. this.onCanvasBlurObservable = new BABYLON.Observable();
  11196. /**
  11197. * Observable event triggered each time the canvas gains focus
  11198. */
  11199. this.onCanvasFocusObservable = new BABYLON.Observable();
  11200. /**
  11201. * Observable event triggered each time the canvas receives pointerout event
  11202. */
  11203. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11204. /**
  11205. * Observable event triggered before each texture is initialized
  11206. */
  11207. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11208. //WebVR
  11209. this._vrDisplay = undefined;
  11210. this._vrSupported = false;
  11211. this._vrExclusivePointerMode = false;
  11212. // Uniform buffers list
  11213. /**
  11214. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11215. */
  11216. this.disableUniformBuffers = false;
  11217. /** @hidden */
  11218. this._uniformBuffers = new Array();
  11219. // Observables
  11220. /**
  11221. * Observable raised when the engine begins a new frame
  11222. */
  11223. this.onBeginFrameObservable = new BABYLON.Observable();
  11224. /**
  11225. * Observable raised when the engine ends the current frame
  11226. */
  11227. this.onEndFrameObservable = new BABYLON.Observable();
  11228. /**
  11229. * Observable raised when the engine is about to compile a shader
  11230. */
  11231. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11232. /**
  11233. * Observable raised when the engine has jsut compiled a shader
  11234. */
  11235. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11236. this._windowIsBackground = false;
  11237. this._webGLVersion = 1.0;
  11238. /** @hidden */
  11239. this._badOS = false;
  11240. /** @hidden */
  11241. this._badDesktopOS = false;
  11242. /**
  11243. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11244. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11245. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11246. */
  11247. this.disableTextureBindingOptimization = false;
  11248. /**
  11249. * Observable signaled when VR display mode changes
  11250. */
  11251. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11252. /**
  11253. * Observable signaled when VR request present is complete
  11254. */
  11255. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11256. /**
  11257. * Observable signaled when VR request present starts
  11258. */
  11259. this.onVRRequestPresentStart = new BABYLON.Observable();
  11260. this._colorWrite = true;
  11261. /** @hidden */
  11262. this._drawCalls = new BABYLON.PerfCounter();
  11263. /** @hidden */
  11264. this._textureCollisions = new BABYLON.PerfCounter();
  11265. this._renderingQueueLaunched = false;
  11266. this._activeRenderLoops = new Array();
  11267. // Deterministic lockstepMaxSteps
  11268. this._deterministicLockstep = false;
  11269. this._lockstepMaxSteps = 4;
  11270. // Lost context
  11271. /**
  11272. * Observable signaled when a context lost event is raised
  11273. */
  11274. this.onContextLostObservable = new BABYLON.Observable();
  11275. /**
  11276. * Observable signaled when a context restored event is raised
  11277. */
  11278. this.onContextRestoredObservable = new BABYLON.Observable();
  11279. this._contextWasLost = false;
  11280. this._doNotHandleContextLost = false;
  11281. // FPS
  11282. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11283. this._fps = 60;
  11284. this._deltaTime = 0;
  11285. /**
  11286. * Turn this value on if you want to pause FPS computation when in background
  11287. */
  11288. this.disablePerformanceMonitorInBackground = false;
  11289. // States
  11290. /** @hidden */
  11291. this._depthCullingState = new BABYLON._DepthCullingState();
  11292. /** @hidden */
  11293. this._stencilState = new BABYLON._StencilState();
  11294. /** @hidden */
  11295. this._alphaState = new BABYLON._AlphaState();
  11296. /** @hidden */
  11297. this._alphaMode = Engine.ALPHA_DISABLE;
  11298. // Cache
  11299. this._internalTexturesCache = new Array();
  11300. /** @hidden */
  11301. this._activeChannel = 0;
  11302. this._currentTextureChannel = -1;
  11303. /** @hidden */
  11304. this._boundTexturesCache = {};
  11305. this._compiledEffects = {};
  11306. this._vertexAttribArraysEnabled = [];
  11307. this._uintIndicesCurrentlySet = false;
  11308. this._currentBoundBuffer = new Array();
  11309. this._currentBufferPointers = new Array();
  11310. this._currentInstanceLocations = new Array();
  11311. this._currentInstanceBuffers = new Array();
  11312. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11313. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11314. this._vaoRecordInProgress = false;
  11315. this._mustWipeVertexAttributes = false;
  11316. this._nextFreeTextureSlots = new Array();
  11317. this._maxSimultaneousTextures = 0;
  11318. this._activeRequests = new Array();
  11319. // Hardware supported Compressed Textures
  11320. this._texturesSupported = new Array();
  11321. this._onVRFullScreenTriggered = function () {
  11322. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11323. //get the old size before we change
  11324. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11325. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11326. //get the width and height, change the render size
  11327. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11328. _this.setHardwareScalingLevel(1);
  11329. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11330. }
  11331. else {
  11332. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11333. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11334. }
  11335. };
  11336. this._boundUniforms = {};
  11337. // Register promises
  11338. BABYLON.PromisePolyfill.Apply();
  11339. var canvas = null;
  11340. Engine.Instances.push(this);
  11341. if (!canvasOrContext) {
  11342. return;
  11343. }
  11344. options = options || {};
  11345. if (canvasOrContext.getContext) {
  11346. canvas = canvasOrContext;
  11347. this._renderingCanvas = canvas;
  11348. if (antialias != null) {
  11349. options.antialias = antialias;
  11350. }
  11351. if (options.deterministicLockstep === undefined) {
  11352. options.deterministicLockstep = false;
  11353. }
  11354. if (options.lockstepMaxSteps === undefined) {
  11355. options.lockstepMaxSteps = 4;
  11356. }
  11357. if (options.preserveDrawingBuffer === undefined) {
  11358. options.preserveDrawingBuffer = false;
  11359. }
  11360. if (options.audioEngine === undefined) {
  11361. options.audioEngine = true;
  11362. }
  11363. if (options.stencil === undefined) {
  11364. options.stencil = true;
  11365. }
  11366. this._deterministicLockstep = options.deterministicLockstep;
  11367. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11368. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11369. // Exceptions
  11370. if (navigator && navigator.userAgent) {
  11371. var ua = navigator.userAgent;
  11372. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11373. var exception = _a[_i];
  11374. var key = exception.key;
  11375. var targets = exception.targets;
  11376. if (ua.indexOf(key) > -1) {
  11377. if (exception.capture && exception.captureConstraint) {
  11378. var capture = exception.capture;
  11379. var constraint = exception.captureConstraint;
  11380. var regex = new RegExp(capture);
  11381. var matches = regex.exec(ua);
  11382. if (matches && matches.length > 0) {
  11383. var capturedValue = parseInt(matches[matches.length - 1]);
  11384. if (capturedValue >= constraint) {
  11385. continue;
  11386. }
  11387. }
  11388. }
  11389. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11390. var target = targets_1[_b];
  11391. switch (target) {
  11392. case "uniformBuffer":
  11393. this.disableUniformBuffers = true;
  11394. break;
  11395. case "textureBindingOptimization":
  11396. this.disableTextureBindingOptimization = true;
  11397. break;
  11398. }
  11399. }
  11400. }
  11401. }
  11402. }
  11403. // GL
  11404. if (!options.disableWebGL2Support) {
  11405. try {
  11406. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11407. if (this._gl) {
  11408. this._webGLVersion = 2.0;
  11409. }
  11410. }
  11411. catch (e) {
  11412. // Do nothing
  11413. }
  11414. }
  11415. if (!this._gl) {
  11416. if (!canvas) {
  11417. throw new Error("The provided canvas is null or undefined.");
  11418. }
  11419. try {
  11420. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11421. }
  11422. catch (e) {
  11423. throw new Error("WebGL not supported");
  11424. }
  11425. }
  11426. if (!this._gl) {
  11427. throw new Error("WebGL not supported");
  11428. }
  11429. this._onCanvasFocus = function () {
  11430. _this.onCanvasFocusObservable.notifyObservers(_this);
  11431. };
  11432. this._onCanvasBlur = function () {
  11433. _this.onCanvasBlurObservable.notifyObservers(_this);
  11434. };
  11435. canvas.addEventListener("focus", this._onCanvasFocus);
  11436. canvas.addEventListener("blur", this._onCanvasBlur);
  11437. this._onBlur = function () {
  11438. if (_this.disablePerformanceMonitorInBackground) {
  11439. _this._performanceMonitor.disable();
  11440. }
  11441. _this._windowIsBackground = true;
  11442. };
  11443. this._onFocus = function () {
  11444. if (_this.disablePerformanceMonitorInBackground) {
  11445. _this._performanceMonitor.enable();
  11446. }
  11447. _this._windowIsBackground = false;
  11448. };
  11449. this._onCanvasPointerOut = function (ev) {
  11450. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11451. };
  11452. window.addEventListener("blur", this._onBlur);
  11453. window.addEventListener("focus", this._onFocus);
  11454. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11455. // Context lost
  11456. if (!this._doNotHandleContextLost) {
  11457. this._onContextLost = function (evt) {
  11458. evt.preventDefault();
  11459. _this._contextWasLost = true;
  11460. BABYLON.Tools.Warn("WebGL context lost.");
  11461. _this.onContextLostObservable.notifyObservers(_this);
  11462. };
  11463. this._onContextRestored = function (evt) {
  11464. // Adding a timeout to avoid race condition at browser level
  11465. setTimeout(function () {
  11466. // Rebuild gl context
  11467. _this._initGLContext();
  11468. // Rebuild effects
  11469. _this._rebuildEffects();
  11470. // Rebuild textures
  11471. _this._rebuildInternalTextures();
  11472. // Rebuild buffers
  11473. _this._rebuildBuffers();
  11474. // Cache
  11475. _this.wipeCaches(true);
  11476. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11477. _this.onContextRestoredObservable.notifyObservers(_this);
  11478. _this._contextWasLost = false;
  11479. }, 0);
  11480. };
  11481. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11482. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11483. }
  11484. }
  11485. else {
  11486. this._gl = canvasOrContext;
  11487. this._renderingCanvas = this._gl.canvas;
  11488. if (this._gl.renderbufferStorageMultisample) {
  11489. this._webGLVersion = 2.0;
  11490. }
  11491. options.stencil = this._gl.getContextAttributes().stencil;
  11492. }
  11493. // Viewport
  11494. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11495. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11496. this.resize();
  11497. this._isStencilEnable = options.stencil ? true : false;
  11498. this._initGLContext();
  11499. if (canvas) {
  11500. // Fullscreen
  11501. this._onFullscreenChange = function () {
  11502. if (document.fullscreen !== undefined) {
  11503. _this.isFullscreen = document.fullscreen;
  11504. }
  11505. else if (document.mozFullScreen !== undefined) {
  11506. _this.isFullscreen = document.mozFullScreen;
  11507. }
  11508. else if (document.webkitIsFullScreen !== undefined) {
  11509. _this.isFullscreen = document.webkitIsFullScreen;
  11510. }
  11511. else if (document.msIsFullScreen !== undefined) {
  11512. _this.isFullscreen = document.msIsFullScreen;
  11513. }
  11514. // Pointer lock
  11515. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11516. canvas.requestPointerLock = canvas.requestPointerLock ||
  11517. canvas.msRequestPointerLock ||
  11518. canvas.mozRequestPointerLock ||
  11519. canvas.webkitRequestPointerLock;
  11520. if (canvas.requestPointerLock) {
  11521. canvas.requestPointerLock();
  11522. }
  11523. }
  11524. };
  11525. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11526. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11527. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11528. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11529. // Pointer lock
  11530. this._onPointerLockChange = function () {
  11531. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11532. document.webkitPointerLockElement === canvas ||
  11533. document.msPointerLockElement === canvas ||
  11534. document.pointerLockElement === canvas);
  11535. };
  11536. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11537. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11538. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11539. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11540. this._onVRDisplayPointerRestricted = function () {
  11541. if (canvas) {
  11542. canvas.requestPointerLock();
  11543. }
  11544. };
  11545. this._onVRDisplayPointerUnrestricted = function () {
  11546. document.exitPointerLock();
  11547. };
  11548. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11549. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11550. }
  11551. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11552. Engine.audioEngine = new BABYLON.AudioEngine();
  11553. }
  11554. // Prepare buffer pointers
  11555. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11556. this._currentBufferPointers[i] = new BufferPointer();
  11557. }
  11558. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11559. // Load WebVR Devices
  11560. if (options.autoEnableWebVR) {
  11561. this.initWebVR();
  11562. }
  11563. // Detect if we are running on a faulty buggy OS.
  11564. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11565. // Detect if we are running on a faulty buggy desktop OS.
  11566. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11567. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11568. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11569. }
  11570. Object.defineProperty(Engine, "LastCreatedEngine", {
  11571. /**
  11572. * Gets the latest created engine
  11573. */
  11574. get: function () {
  11575. if (Engine.Instances.length === 0) {
  11576. return null;
  11577. }
  11578. return Engine.Instances[Engine.Instances.length - 1];
  11579. },
  11580. enumerable: true,
  11581. configurable: true
  11582. });
  11583. Object.defineProperty(Engine, "LastCreatedScene", {
  11584. /**
  11585. * Gets the latest created scene
  11586. */
  11587. get: function () {
  11588. var lastCreatedEngine = Engine.LastCreatedEngine;
  11589. if (!lastCreatedEngine) {
  11590. return null;
  11591. }
  11592. if (lastCreatedEngine.scenes.length === 0) {
  11593. return null;
  11594. }
  11595. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11596. },
  11597. enumerable: true,
  11598. configurable: true
  11599. });
  11600. /**
  11601. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11602. * @param flag defines which part of the materials must be marked as dirty
  11603. * @param predicate defines a predicate used to filter which materials should be affected
  11604. */
  11605. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11606. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11607. var engine = Engine.Instances[engineIndex];
  11608. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11609. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11610. }
  11611. }
  11612. };
  11613. Object.defineProperty(Engine, "NEVER", {
  11614. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11615. get: function () {
  11616. return Engine._NEVER;
  11617. },
  11618. enumerable: true,
  11619. configurable: true
  11620. });
  11621. Object.defineProperty(Engine, "ALWAYS", {
  11622. /** 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 */
  11623. get: function () {
  11624. return Engine._ALWAYS;
  11625. },
  11626. enumerable: true,
  11627. configurable: true
  11628. });
  11629. Object.defineProperty(Engine, "LESS", {
  11630. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11631. get: function () {
  11632. return Engine._LESS;
  11633. },
  11634. enumerable: true,
  11635. configurable: true
  11636. });
  11637. Object.defineProperty(Engine, "EQUAL", {
  11638. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11639. get: function () {
  11640. return Engine._EQUAL;
  11641. },
  11642. enumerable: true,
  11643. configurable: true
  11644. });
  11645. Object.defineProperty(Engine, "LEQUAL", {
  11646. /** 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 */
  11647. get: function () {
  11648. return Engine._LEQUAL;
  11649. },
  11650. enumerable: true,
  11651. configurable: true
  11652. });
  11653. Object.defineProperty(Engine, "GREATER", {
  11654. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11655. get: function () {
  11656. return Engine._GREATER;
  11657. },
  11658. enumerable: true,
  11659. configurable: true
  11660. });
  11661. Object.defineProperty(Engine, "GEQUAL", {
  11662. /** 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 */
  11663. get: function () {
  11664. return Engine._GEQUAL;
  11665. },
  11666. enumerable: true,
  11667. configurable: true
  11668. });
  11669. Object.defineProperty(Engine, "NOTEQUAL", {
  11670. /** 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 */
  11671. get: function () {
  11672. return Engine._NOTEQUAL;
  11673. },
  11674. enumerable: true,
  11675. configurable: true
  11676. });
  11677. Object.defineProperty(Engine, "KEEP", {
  11678. /** Passed to stencilOperation to specify that stencil value must be kept */
  11679. get: function () {
  11680. return Engine._KEEP;
  11681. },
  11682. enumerable: true,
  11683. configurable: true
  11684. });
  11685. Object.defineProperty(Engine, "REPLACE", {
  11686. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11687. get: function () {
  11688. return Engine._REPLACE;
  11689. },
  11690. enumerable: true,
  11691. configurable: true
  11692. });
  11693. Object.defineProperty(Engine, "INCR", {
  11694. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11695. get: function () {
  11696. return Engine._INCR;
  11697. },
  11698. enumerable: true,
  11699. configurable: true
  11700. });
  11701. Object.defineProperty(Engine, "DECR", {
  11702. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11703. get: function () {
  11704. return Engine._DECR;
  11705. },
  11706. enumerable: true,
  11707. configurable: true
  11708. });
  11709. Object.defineProperty(Engine, "INVERT", {
  11710. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11711. get: function () {
  11712. return Engine._INVERT;
  11713. },
  11714. enumerable: true,
  11715. configurable: true
  11716. });
  11717. Object.defineProperty(Engine, "INCR_WRAP", {
  11718. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11719. get: function () {
  11720. return Engine._INCR_WRAP;
  11721. },
  11722. enumerable: true,
  11723. configurable: true
  11724. });
  11725. Object.defineProperty(Engine, "DECR_WRAP", {
  11726. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11727. get: function () {
  11728. return Engine._DECR_WRAP;
  11729. },
  11730. enumerable: true,
  11731. configurable: true
  11732. });
  11733. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11734. // Alpha
  11735. /** Defines that alpha blending is disabled */
  11736. get: function () {
  11737. return Engine._ALPHA_DISABLE;
  11738. },
  11739. enumerable: true,
  11740. configurable: true
  11741. });
  11742. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11743. /** Defines that alpha blending to SRC + DEST */
  11744. get: function () {
  11745. return Engine._ALPHA_ONEONE;
  11746. },
  11747. enumerable: true,
  11748. configurable: true
  11749. });
  11750. Object.defineProperty(Engine, "ALPHA_ADD", {
  11751. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11752. get: function () {
  11753. return Engine._ALPHA_ADD;
  11754. },
  11755. enumerable: true,
  11756. configurable: true
  11757. });
  11758. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11759. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11760. get: function () {
  11761. return Engine._ALPHA_COMBINE;
  11762. },
  11763. enumerable: true,
  11764. configurable: true
  11765. });
  11766. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11767. /** Defines that alpha blending to DEST - SRC * DEST */
  11768. get: function () {
  11769. return Engine._ALPHA_SUBTRACT;
  11770. },
  11771. enumerable: true,
  11772. configurable: true
  11773. });
  11774. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11775. /** Defines that alpha blending to SRC * DEST */
  11776. get: function () {
  11777. return Engine._ALPHA_MULTIPLY;
  11778. },
  11779. enumerable: true,
  11780. configurable: true
  11781. });
  11782. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11783. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11784. get: function () {
  11785. return Engine._ALPHA_MAXIMIZED;
  11786. },
  11787. enumerable: true,
  11788. configurable: true
  11789. });
  11790. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11791. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11792. get: function () {
  11793. return Engine._ALPHA_PREMULTIPLIED;
  11794. },
  11795. enumerable: true,
  11796. configurable: true
  11797. });
  11798. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11799. /**
  11800. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11801. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11802. */
  11803. get: function () {
  11804. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11805. },
  11806. enumerable: true,
  11807. configurable: true
  11808. });
  11809. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11810. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11811. get: function () {
  11812. return Engine._ALPHA_INTERPOLATE;
  11813. },
  11814. enumerable: true,
  11815. configurable: true
  11816. });
  11817. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11818. /**
  11819. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11820. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11821. */
  11822. get: function () {
  11823. return Engine._ALPHA_SCREENMODE;
  11824. },
  11825. enumerable: true,
  11826. configurable: true
  11827. });
  11828. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11829. // Delays
  11830. /** Defines that the ressource is not delayed*/
  11831. get: function () {
  11832. return Engine._DELAYLOADSTATE_NONE;
  11833. },
  11834. enumerable: true,
  11835. configurable: true
  11836. });
  11837. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11838. /** Defines that the ressource was successfully delay loaded */
  11839. get: function () {
  11840. return Engine._DELAYLOADSTATE_LOADED;
  11841. },
  11842. enumerable: true,
  11843. configurable: true
  11844. });
  11845. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11846. /** Defines that the ressource is currently delay loading */
  11847. get: function () {
  11848. return Engine._DELAYLOADSTATE_LOADING;
  11849. },
  11850. enumerable: true,
  11851. configurable: true
  11852. });
  11853. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11854. /** Defines that the ressource is delayed and has not started loading */
  11855. get: function () {
  11856. return Engine._DELAYLOADSTATE_NOTLOADED;
  11857. },
  11858. enumerable: true,
  11859. configurable: true
  11860. });
  11861. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11862. /** ALPHA */
  11863. get: function () {
  11864. return Engine._TEXTUREFORMAT_ALPHA;
  11865. },
  11866. enumerable: true,
  11867. configurable: true
  11868. });
  11869. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11870. /** LUMINANCE */
  11871. get: function () {
  11872. return Engine._TEXTUREFORMAT_LUMINANCE;
  11873. },
  11874. enumerable: true,
  11875. configurable: true
  11876. });
  11877. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11878. /**
  11879. * R32F
  11880. */
  11881. get: function () {
  11882. return Engine._TEXTUREFORMAT_R32F;
  11883. },
  11884. enumerable: true,
  11885. configurable: true
  11886. });
  11887. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11888. /**
  11889. * RG32F
  11890. */
  11891. get: function () {
  11892. return Engine._TEXTUREFORMAT_RG32F;
  11893. },
  11894. enumerable: true,
  11895. configurable: true
  11896. });
  11897. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11898. /**
  11899. * RGB32F
  11900. */
  11901. get: function () {
  11902. return Engine._TEXTUREFORMAT_RGB32F;
  11903. },
  11904. enumerable: true,
  11905. configurable: true
  11906. });
  11907. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11908. /**
  11909. * RGBA32F
  11910. */
  11911. get: function () {
  11912. return Engine._TEXTUREFORMAT_RGBA32F;
  11913. },
  11914. enumerable: true,
  11915. configurable: true
  11916. });
  11917. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11918. /** LUMINANCE_ALPHA */
  11919. get: function () {
  11920. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11921. },
  11922. enumerable: true,
  11923. configurable: true
  11924. });
  11925. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11926. /** RGB */
  11927. get: function () {
  11928. return Engine._TEXTUREFORMAT_RGB;
  11929. },
  11930. enumerable: true,
  11931. configurable: true
  11932. });
  11933. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11934. /** RGBA */
  11935. get: function () {
  11936. return Engine._TEXTUREFORMAT_RGBA;
  11937. },
  11938. enumerable: true,
  11939. configurable: true
  11940. });
  11941. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11942. /** UNSIGNED_INT */
  11943. get: function () {
  11944. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11945. },
  11946. enumerable: true,
  11947. configurable: true
  11948. });
  11949. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11950. /** FLOAT */
  11951. get: function () {
  11952. return Engine._TEXTURETYPE_FLOAT;
  11953. },
  11954. enumerable: true,
  11955. configurable: true
  11956. });
  11957. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11958. /** HALF_FLOAT */
  11959. get: function () {
  11960. return Engine._TEXTURETYPE_HALF_FLOAT;
  11961. },
  11962. enumerable: true,
  11963. configurable: true
  11964. });
  11965. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11966. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11967. get: function () {
  11968. return Engine._SCALEMODE_FLOOR;
  11969. },
  11970. enumerable: true,
  11971. configurable: true
  11972. });
  11973. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11974. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11975. get: function () {
  11976. return Engine._SCALEMODE_NEAREST;
  11977. },
  11978. enumerable: true,
  11979. configurable: true
  11980. });
  11981. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11982. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11983. get: function () {
  11984. return Engine._SCALEMODE_CEILING;
  11985. },
  11986. enumerable: true,
  11987. configurable: true
  11988. });
  11989. Object.defineProperty(Engine, "Version", {
  11990. /**
  11991. * Returns the current version of the framework
  11992. */
  11993. get: function () {
  11994. return "3.2.0-rc.4";
  11995. },
  11996. enumerable: true,
  11997. configurable: true
  11998. });
  11999. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12000. /**
  12001. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12002. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12003. */
  12004. get: function () {
  12005. return this._vrExclusivePointerMode;
  12006. },
  12007. enumerable: true,
  12008. configurable: true
  12009. });
  12010. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12011. /**
  12012. * Gets a boolean indicating that the engine supports uniform buffers
  12013. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12014. */
  12015. get: function () {
  12016. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12017. },
  12018. enumerable: true,
  12019. configurable: true
  12020. });
  12021. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12022. /**
  12023. * Gets a boolean indicating that only power of 2 textures are supported
  12024. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12025. */
  12026. get: function () {
  12027. return this._webGLVersion < 2 || this.forcePOTTextures;
  12028. },
  12029. enumerable: true,
  12030. configurable: true
  12031. });
  12032. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12033. /**
  12034. * Gets the performance monitor attached to this engine
  12035. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12036. */
  12037. get: function () {
  12038. return this._performanceMonitor;
  12039. },
  12040. enumerable: true,
  12041. configurable: true
  12042. });
  12043. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12044. /**
  12045. * Gets the list of texture formats supported
  12046. */
  12047. get: function () {
  12048. return this._texturesSupported;
  12049. },
  12050. enumerable: true,
  12051. configurable: true
  12052. });
  12053. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12054. /**
  12055. * Gets the list of texture formats in use
  12056. */
  12057. get: function () {
  12058. return this._textureFormatInUse;
  12059. },
  12060. enumerable: true,
  12061. configurable: true
  12062. });
  12063. Object.defineProperty(Engine.prototype, "currentViewport", {
  12064. /**
  12065. * Gets the current viewport
  12066. */
  12067. get: function () {
  12068. return this._cachedViewport;
  12069. },
  12070. enumerable: true,
  12071. configurable: true
  12072. });
  12073. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12074. /**
  12075. * Gets the default empty texture
  12076. */
  12077. get: function () {
  12078. if (!this._emptyTexture) {
  12079. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12080. }
  12081. return this._emptyTexture;
  12082. },
  12083. enumerable: true,
  12084. configurable: true
  12085. });
  12086. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12087. /**
  12088. * Gets the default empty 3D texture
  12089. */
  12090. get: function () {
  12091. if (!this._emptyTexture3D) {
  12092. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12093. }
  12094. return this._emptyTexture3D;
  12095. },
  12096. enumerable: true,
  12097. configurable: true
  12098. });
  12099. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12100. /**
  12101. * Gets the default empty cube texture
  12102. */
  12103. get: function () {
  12104. if (!this._emptyCubeTexture) {
  12105. var faceData = new Uint8Array(4);
  12106. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12107. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12108. }
  12109. return this._emptyCubeTexture;
  12110. },
  12111. enumerable: true,
  12112. configurable: true
  12113. });
  12114. Engine.prototype._rebuildInternalTextures = function () {
  12115. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12116. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12117. var internalTexture = currentState_1[_i];
  12118. internalTexture._rebuild();
  12119. }
  12120. };
  12121. Engine.prototype._rebuildEffects = function () {
  12122. for (var key in this._compiledEffects) {
  12123. var effect = this._compiledEffects[key];
  12124. effect._prepareEffect();
  12125. }
  12126. BABYLON.Effect.ResetCache();
  12127. };
  12128. Engine.prototype._rebuildBuffers = function () {
  12129. // Index / Vertex
  12130. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12131. var scene = _a[_i];
  12132. scene.resetCachedMaterial();
  12133. scene._rebuildGeometries();
  12134. scene._rebuildTextures();
  12135. }
  12136. // Uniforms
  12137. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12138. var uniformBuffer = _c[_b];
  12139. uniformBuffer._rebuild();
  12140. }
  12141. };
  12142. Engine.prototype._initGLContext = function () {
  12143. // Caps
  12144. this._caps = new EngineCapabilities();
  12145. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12146. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12147. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12148. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12149. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12150. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12151. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12152. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12153. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12154. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12155. // Infos
  12156. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12157. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12158. if (rendererInfo != null) {
  12159. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12160. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12161. }
  12162. if (!this._glVendor) {
  12163. this._glVendor = "Unknown vendor";
  12164. }
  12165. if (!this._glRenderer) {
  12166. this._glRenderer = "Unknown renderer";
  12167. }
  12168. // Constants
  12169. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12170. if (this._gl.RGBA16F !== 0x881A) {
  12171. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12172. }
  12173. if (this._gl.RGBA32F !== 0x8814) {
  12174. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12175. }
  12176. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12177. this._gl.DEPTH24_STENCIL8 = 35056;
  12178. }
  12179. // Extensions
  12180. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12181. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12182. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12183. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12184. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12185. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12186. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12187. 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');
  12188. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12189. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12190. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12191. this._caps.highPrecisionShaderSupported = true;
  12192. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12193. if (this._caps.timerQuery) {
  12194. if (this._webGLVersion === 1) {
  12195. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12196. }
  12197. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12198. }
  12199. // Checks if some of the format renders first to allow the use of webgl inspector.
  12200. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12201. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12202. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12203. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12204. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12205. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12206. if (this._webGLVersion > 1) {
  12207. this._gl.HALF_FLOAT_OES = 0x140B;
  12208. }
  12209. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12210. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12211. // Draw buffers
  12212. if (this._webGLVersion > 1) {
  12213. this._caps.drawBuffersExtension = true;
  12214. }
  12215. else {
  12216. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12217. if (drawBuffersExtension !== null) {
  12218. this._caps.drawBuffersExtension = true;
  12219. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12220. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12221. for (var i = 0; i < 16; i++) {
  12222. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12223. }
  12224. }
  12225. else {
  12226. this._caps.drawBuffersExtension = false;
  12227. }
  12228. }
  12229. // Depth Texture
  12230. if (this._webGLVersion > 1) {
  12231. this._caps.depthTextureExtension = true;
  12232. }
  12233. else {
  12234. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12235. if (depthTextureExtension != null) {
  12236. this._caps.depthTextureExtension = true;
  12237. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12238. }
  12239. }
  12240. // Vertex array object
  12241. if (this._webGLVersion > 1) {
  12242. this._caps.vertexArrayObject = true;
  12243. }
  12244. else {
  12245. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12246. if (vertexArrayObjectExtension != null) {
  12247. this._caps.vertexArrayObject = true;
  12248. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12249. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12250. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12251. }
  12252. else {
  12253. this._caps.vertexArrayObject = false;
  12254. }
  12255. }
  12256. // Instances count
  12257. if (this._webGLVersion > 1) {
  12258. this._caps.instancedArrays = true;
  12259. }
  12260. else {
  12261. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12262. if (instanceExtension != null) {
  12263. this._caps.instancedArrays = true;
  12264. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12265. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12266. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12267. }
  12268. else {
  12269. this._caps.instancedArrays = false;
  12270. }
  12271. }
  12272. // Intelligently add supported compressed formats in order to check for.
  12273. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12274. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12275. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12276. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12277. if (this._caps.astc)
  12278. this.texturesSupported.push('-astc.ktx');
  12279. if (this._caps.s3tc)
  12280. this.texturesSupported.push('-dxt.ktx');
  12281. if (this._caps.pvrtc)
  12282. this.texturesSupported.push('-pvrtc.ktx');
  12283. if (this._caps.etc2)
  12284. this.texturesSupported.push('-etc2.ktx');
  12285. if (this._caps.etc1)
  12286. this.texturesSupported.push('-etc1.ktx');
  12287. if (this._gl.getShaderPrecisionFormat) {
  12288. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12289. if (highp) {
  12290. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12291. }
  12292. }
  12293. // Depth buffer
  12294. this.setDepthBuffer(true);
  12295. this.setDepthFunctionToLessOrEqual();
  12296. this.setDepthWrite(true);
  12297. // Texture maps
  12298. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12299. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12300. this._nextFreeTextureSlots.push(slot);
  12301. }
  12302. };
  12303. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12304. /**
  12305. * Gets version of the current webGL context
  12306. */
  12307. get: function () {
  12308. return this._webGLVersion;
  12309. },
  12310. enumerable: true,
  12311. configurable: true
  12312. });
  12313. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12314. /**
  12315. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12316. */
  12317. get: function () {
  12318. return this._isStencilEnable;
  12319. },
  12320. enumerable: true,
  12321. configurable: true
  12322. });
  12323. Engine.prototype._prepareWorkingCanvas = function () {
  12324. if (this._workingCanvas) {
  12325. return;
  12326. }
  12327. this._workingCanvas = document.createElement("canvas");
  12328. var context = this._workingCanvas.getContext("2d");
  12329. if (context) {
  12330. this._workingContext = context;
  12331. }
  12332. };
  12333. /**
  12334. * Reset the texture cache to empty state
  12335. */
  12336. Engine.prototype.resetTextureCache = function () {
  12337. for (var key in this._boundTexturesCache) {
  12338. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12339. continue;
  12340. }
  12341. var boundTexture = this._boundTexturesCache[key];
  12342. if (boundTexture) {
  12343. this._removeDesignatedSlot(boundTexture);
  12344. }
  12345. this._boundTexturesCache[key] = null;
  12346. }
  12347. if (!this.disableTextureBindingOptimization) {
  12348. this._nextFreeTextureSlots = [];
  12349. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12350. this._nextFreeTextureSlots.push(slot);
  12351. }
  12352. }
  12353. this._currentTextureChannel = -1;
  12354. };
  12355. /**
  12356. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12357. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12358. * @returns true if engine is in deterministic lock step mode
  12359. */
  12360. Engine.prototype.isDeterministicLockStep = function () {
  12361. return this._deterministicLockstep;
  12362. };
  12363. /**
  12364. * Gets the max steps when engine is running in deterministic lock step
  12365. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12366. * @returns the max steps
  12367. */
  12368. Engine.prototype.getLockstepMaxSteps = function () {
  12369. return this._lockstepMaxSteps;
  12370. };
  12371. /**
  12372. * Gets an object containing information about the current webGL context
  12373. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12374. */
  12375. Engine.prototype.getGlInfo = function () {
  12376. return {
  12377. vendor: this._glVendor,
  12378. renderer: this._glRenderer,
  12379. version: this._glVersion
  12380. };
  12381. };
  12382. /**
  12383. * Gets current aspect ratio
  12384. * @param camera defines the camera to use to get the aspect ratio
  12385. * @param useScreen defines if screen size must be used (or the current render target if any)
  12386. * @returns a number defining the aspect ratio
  12387. */
  12388. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12389. if (useScreen === void 0) { useScreen = false; }
  12390. var viewport = camera.viewport;
  12391. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12392. };
  12393. /**
  12394. * Gets the current render width
  12395. * @param useScreen defines if screen size must be used (or the current render target if any)
  12396. * @returns a number defining the current render width
  12397. */
  12398. Engine.prototype.getRenderWidth = function (useScreen) {
  12399. if (useScreen === void 0) { useScreen = false; }
  12400. if (!useScreen && this._currentRenderTarget) {
  12401. return this._currentRenderTarget.width;
  12402. }
  12403. return this._gl.drawingBufferWidth;
  12404. };
  12405. /**
  12406. * Gets the current render height
  12407. * @param useScreen defines if screen size must be used (or the current render target if any)
  12408. * @returns a number defining the current render height
  12409. */
  12410. Engine.prototype.getRenderHeight = function (useScreen) {
  12411. if (useScreen === void 0) { useScreen = false; }
  12412. if (!useScreen && this._currentRenderTarget) {
  12413. return this._currentRenderTarget.height;
  12414. }
  12415. return this._gl.drawingBufferHeight;
  12416. };
  12417. /**
  12418. * Gets the HTML canvas attached with the current webGL context
  12419. * @returns a HTML canvas
  12420. */
  12421. Engine.prototype.getRenderingCanvas = function () {
  12422. return this._renderingCanvas;
  12423. };
  12424. /**
  12425. * Gets the client rect of the HTML canvas attached with the current webGL context
  12426. * @returns a client rectanglee
  12427. */
  12428. Engine.prototype.getRenderingCanvasClientRect = function () {
  12429. if (!this._renderingCanvas) {
  12430. return null;
  12431. }
  12432. return this._renderingCanvas.getBoundingClientRect();
  12433. };
  12434. /**
  12435. * Defines the hardware scaling level.
  12436. * By default the hardware scaling level is computed from the window device ratio.
  12437. * 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.
  12438. * @param level defines the level to use
  12439. */
  12440. Engine.prototype.setHardwareScalingLevel = function (level) {
  12441. this._hardwareScalingLevel = level;
  12442. this.resize();
  12443. };
  12444. /**
  12445. * Gets the current hardware scaling level.
  12446. * By default the hardware scaling level is computed from the window device ratio.
  12447. * 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.
  12448. * @returns a number indicating the current hardware scaling level
  12449. */
  12450. Engine.prototype.getHardwareScalingLevel = function () {
  12451. return this._hardwareScalingLevel;
  12452. };
  12453. /**
  12454. * Gets the list of loaded textures
  12455. * @returns an array containing all loaded textures
  12456. */
  12457. Engine.prototype.getLoadedTexturesCache = function () {
  12458. return this._internalTexturesCache;
  12459. };
  12460. /**
  12461. * Gets the object containing all engine capabilities
  12462. * @returns the EngineCapabilities object
  12463. */
  12464. Engine.prototype.getCaps = function () {
  12465. return this._caps;
  12466. };
  12467. Object.defineProperty(Engine.prototype, "drawCalls", {
  12468. /** @hidden */
  12469. get: function () {
  12470. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12471. return 0;
  12472. },
  12473. enumerable: true,
  12474. configurable: true
  12475. });
  12476. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12477. /** @hidden */
  12478. get: function () {
  12479. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12480. return null;
  12481. },
  12482. enumerable: true,
  12483. configurable: true
  12484. });
  12485. /**
  12486. * Gets the current depth function
  12487. * @returns a number defining the depth function
  12488. */
  12489. Engine.prototype.getDepthFunction = function () {
  12490. return this._depthCullingState.depthFunc;
  12491. };
  12492. /**
  12493. * Sets the current depth function
  12494. * @param depthFunc defines the function to use
  12495. */
  12496. Engine.prototype.setDepthFunction = function (depthFunc) {
  12497. this._depthCullingState.depthFunc = depthFunc;
  12498. };
  12499. /**
  12500. * Sets the current depth function to GREATER
  12501. */
  12502. Engine.prototype.setDepthFunctionToGreater = function () {
  12503. this._depthCullingState.depthFunc = this._gl.GREATER;
  12504. };
  12505. /**
  12506. * Sets the current depth function to GEQUAL
  12507. */
  12508. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12509. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12510. };
  12511. /**
  12512. * Sets the current depth function to LESS
  12513. */
  12514. Engine.prototype.setDepthFunctionToLess = function () {
  12515. this._depthCullingState.depthFunc = this._gl.LESS;
  12516. };
  12517. /**
  12518. * Sets the current depth function to LEQUAL
  12519. */
  12520. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12521. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12522. };
  12523. /**
  12524. * Gets a boolean indicating if stencil buffer is enabled
  12525. * @returns the current stencil buffer state
  12526. */
  12527. Engine.prototype.getStencilBuffer = function () {
  12528. return this._stencilState.stencilTest;
  12529. };
  12530. /**
  12531. * Enable or disable the stencil buffer
  12532. * @param enable defines if the stencil buffer must be enabled or disabled
  12533. */
  12534. Engine.prototype.setStencilBuffer = function (enable) {
  12535. this._stencilState.stencilTest = enable;
  12536. };
  12537. /**
  12538. * Gets the current stencil mask
  12539. * @returns a number defining the new stencil mask to use
  12540. */
  12541. Engine.prototype.getStencilMask = function () {
  12542. return this._stencilState.stencilMask;
  12543. };
  12544. /**
  12545. * Sets the current stencil mask
  12546. * @param mask defines the new stencil mask to use
  12547. */
  12548. Engine.prototype.setStencilMask = function (mask) {
  12549. this._stencilState.stencilMask = mask;
  12550. };
  12551. /**
  12552. * Gets the current stencil function
  12553. * @returns a number defining the stencil function to use
  12554. */
  12555. Engine.prototype.getStencilFunction = function () {
  12556. return this._stencilState.stencilFunc;
  12557. };
  12558. /**
  12559. * Gets the current stencil reference value
  12560. * @returns a number defining the stencil reference value to use
  12561. */
  12562. Engine.prototype.getStencilFunctionReference = function () {
  12563. return this._stencilState.stencilFuncRef;
  12564. };
  12565. /**
  12566. * Gets the current stencil mask
  12567. * @returns a number defining the stencil mask to use
  12568. */
  12569. Engine.prototype.getStencilFunctionMask = function () {
  12570. return this._stencilState.stencilFuncMask;
  12571. };
  12572. /**
  12573. * Sets the current stencil function
  12574. * @param stencilFunc defines the new stencil function to use
  12575. */
  12576. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12577. this._stencilState.stencilFunc = stencilFunc;
  12578. };
  12579. /**
  12580. * Sets the current stencil reference
  12581. * @param reference defines the new stencil reference to use
  12582. */
  12583. Engine.prototype.setStencilFunctionReference = function (reference) {
  12584. this._stencilState.stencilFuncRef = reference;
  12585. };
  12586. /**
  12587. * Sets the current stencil mask
  12588. * @param mask defines the new stencil mask to use
  12589. */
  12590. Engine.prototype.setStencilFunctionMask = function (mask) {
  12591. this._stencilState.stencilFuncMask = mask;
  12592. };
  12593. /**
  12594. * Gets the current stencil operation when stencil fails
  12595. * @returns a number defining stencil operation to use when stencil fails
  12596. */
  12597. Engine.prototype.getStencilOperationFail = function () {
  12598. return this._stencilState.stencilOpStencilFail;
  12599. };
  12600. /**
  12601. * Gets the current stencil operation when depth fails
  12602. * @returns a number defining stencil operation to use when depth fails
  12603. */
  12604. Engine.prototype.getStencilOperationDepthFail = function () {
  12605. return this._stencilState.stencilOpDepthFail;
  12606. };
  12607. /**
  12608. * Gets the current stencil operation when stencil passes
  12609. * @returns a number defining stencil operation to use when stencil passes
  12610. */
  12611. Engine.prototype.getStencilOperationPass = function () {
  12612. return this._stencilState.stencilOpStencilDepthPass;
  12613. };
  12614. /**
  12615. * Sets the stencil operation to use when stencil fails
  12616. * @param operation defines the stencil operation to use when stencil fails
  12617. */
  12618. Engine.prototype.setStencilOperationFail = function (operation) {
  12619. this._stencilState.stencilOpStencilFail = operation;
  12620. };
  12621. /**
  12622. * Sets the stencil operation to use when depth fails
  12623. * @param operation defines the stencil operation to use when depth fails
  12624. */
  12625. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12626. this._stencilState.stencilOpDepthFail = operation;
  12627. };
  12628. /**
  12629. * Sets the stencil operation to use when stencil passes
  12630. * @param operation defines the stencil operation to use when stencil passes
  12631. */
  12632. Engine.prototype.setStencilOperationPass = function (operation) {
  12633. this._stencilState.stencilOpStencilDepthPass = operation;
  12634. };
  12635. /**
  12636. * Sets a boolean indicating if the dithering state is enabled or disabled
  12637. * @param value defines the dithering state
  12638. */
  12639. Engine.prototype.setDitheringState = function (value) {
  12640. if (value) {
  12641. this._gl.enable(this._gl.DITHER);
  12642. }
  12643. else {
  12644. this._gl.disable(this._gl.DITHER);
  12645. }
  12646. };
  12647. /**
  12648. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12649. * @param value defines the rasterizer state
  12650. */
  12651. Engine.prototype.setRasterizerState = function (value) {
  12652. if (value) {
  12653. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12654. }
  12655. else {
  12656. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12657. }
  12658. };
  12659. /**
  12660. * stop executing a render loop function and remove it from the execution array
  12661. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12662. */
  12663. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12664. if (!renderFunction) {
  12665. this._activeRenderLoops = [];
  12666. return;
  12667. }
  12668. var index = this._activeRenderLoops.indexOf(renderFunction);
  12669. if (index >= 0) {
  12670. this._activeRenderLoops.splice(index, 1);
  12671. }
  12672. };
  12673. /** @hidden */
  12674. Engine.prototype._renderLoop = function () {
  12675. if (!this._contextWasLost) {
  12676. var shouldRender = true;
  12677. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12678. shouldRender = false;
  12679. }
  12680. if (shouldRender) {
  12681. // Start new frame
  12682. this.beginFrame();
  12683. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12684. var renderFunction = this._activeRenderLoops[index];
  12685. renderFunction();
  12686. }
  12687. // Present
  12688. this.endFrame();
  12689. }
  12690. }
  12691. if (this._activeRenderLoops.length > 0) {
  12692. // Register new frame
  12693. var requester = null;
  12694. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12695. requester = this._vrDisplay;
  12696. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12697. }
  12698. else {
  12699. this._renderingQueueLaunched = false;
  12700. }
  12701. };
  12702. /**
  12703. * Register and execute a render loop. The engine can have more than one render function
  12704. * @param renderFunction defines the function to continuously execute
  12705. */
  12706. Engine.prototype.runRenderLoop = function (renderFunction) {
  12707. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12708. return;
  12709. }
  12710. this._activeRenderLoops.push(renderFunction);
  12711. if (!this._renderingQueueLaunched) {
  12712. this._renderingQueueLaunched = true;
  12713. this._bindedRenderFunction = this._renderLoop.bind(this);
  12714. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12715. }
  12716. };
  12717. /**
  12718. * Toggle full screen mode
  12719. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12720. * @param options defines an option object to be sent to the requestFullscreen function
  12721. */
  12722. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12723. if (this.isFullscreen) {
  12724. BABYLON.Tools.ExitFullscreen();
  12725. }
  12726. else {
  12727. this._pointerLockRequested = requestPointerLock;
  12728. if (this._renderingCanvas) {
  12729. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12730. }
  12731. }
  12732. };
  12733. /**
  12734. * Clear the current render buffer or the current render target (if any is set up)
  12735. * @param color defines the color to use
  12736. * @param backBuffer defines if the back buffer must be cleared
  12737. * @param depth defines if the depth buffer must be cleared
  12738. * @param stencil defines if the stencil buffer must be cleared
  12739. */
  12740. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12741. if (stencil === void 0) { stencil = false; }
  12742. this.applyStates();
  12743. var mode = 0;
  12744. if (backBuffer && color) {
  12745. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12746. mode |= this._gl.COLOR_BUFFER_BIT;
  12747. }
  12748. if (depth) {
  12749. this._gl.clearDepth(1.0);
  12750. mode |= this._gl.DEPTH_BUFFER_BIT;
  12751. }
  12752. if (stencil) {
  12753. this._gl.clearStencil(0);
  12754. mode |= this._gl.STENCIL_BUFFER_BIT;
  12755. }
  12756. this._gl.clear(mode);
  12757. };
  12758. /**
  12759. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12760. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12761. * @param y defines the y-coordinate of the corner of the clear rectangle
  12762. * @param width defines the width of the clear rectangle
  12763. * @param height defines the height of the clear rectangle
  12764. * @param clearColor defines the clear color
  12765. */
  12766. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12767. var gl = this._gl;
  12768. // Save state
  12769. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12770. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12771. // Change state
  12772. gl.enable(gl.SCISSOR_TEST);
  12773. gl.scissor(x, y, width, height);
  12774. // Clear
  12775. this.clear(clearColor, true, true, true);
  12776. // Restore state
  12777. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12778. if (curScissor === true) {
  12779. gl.enable(gl.SCISSOR_TEST);
  12780. }
  12781. else {
  12782. gl.disable(gl.SCISSOR_TEST);
  12783. }
  12784. };
  12785. /**
  12786. * Set the WebGL's viewport
  12787. * @param viewport defines the viewport element to be used
  12788. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12789. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12790. */
  12791. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12792. var width = requiredWidth || this.getRenderWidth();
  12793. var height = requiredHeight || this.getRenderHeight();
  12794. var x = viewport.x || 0;
  12795. var y = viewport.y || 0;
  12796. this._cachedViewport = viewport;
  12797. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12798. };
  12799. /**
  12800. * Directly set the WebGL Viewport
  12801. * @param x defines the x coordinate of the viewport (in screen space)
  12802. * @param y defines the y coordinate of the viewport (in screen space)
  12803. * @param width defines the width of the viewport (in screen space)
  12804. * @param height defines the height of the viewport (in screen space)
  12805. * @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
  12806. */
  12807. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12808. var currentViewport = this._cachedViewport;
  12809. this._cachedViewport = null;
  12810. this._gl.viewport(x, y, width, height);
  12811. return currentViewport;
  12812. };
  12813. /**
  12814. * Begin a new frame
  12815. */
  12816. Engine.prototype.beginFrame = function () {
  12817. this.onBeginFrameObservable.notifyObservers(this);
  12818. this._measureFps();
  12819. };
  12820. /**
  12821. * Enf the current frame
  12822. */
  12823. Engine.prototype.endFrame = function () {
  12824. // Force a flush in case we are using a bad OS.
  12825. if (this._badOS) {
  12826. this.flushFramebuffer();
  12827. }
  12828. // Submit frame to the vr device, if enabled
  12829. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12830. // TODO: We should only submit the frame if we read frameData successfully.
  12831. this._vrDisplay.submitFrame();
  12832. }
  12833. this.onEndFrameObservable.notifyObservers(this);
  12834. };
  12835. /**
  12836. * Resize the view according to the canvas' size
  12837. */
  12838. Engine.prototype.resize = function () {
  12839. // We're not resizing the size of the canvas while in VR mode & presenting
  12840. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12841. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12842. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12843. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12844. }
  12845. };
  12846. /**
  12847. * Force a specific size of the canvas
  12848. * @param width defines the new canvas' width
  12849. * @param height defines the new canvas' height
  12850. */
  12851. Engine.prototype.setSize = function (width, height) {
  12852. if (!this._renderingCanvas) {
  12853. return;
  12854. }
  12855. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12856. return;
  12857. }
  12858. this._renderingCanvas.width = width;
  12859. this._renderingCanvas.height = height;
  12860. for (var index = 0; index < this.scenes.length; index++) {
  12861. var scene = this.scenes[index];
  12862. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12863. var cam = scene.cameras[camIndex];
  12864. cam._currentRenderId = 0;
  12865. }
  12866. }
  12867. if (this.onResizeObservable.hasObservers) {
  12868. this.onResizeObservable.notifyObservers(this);
  12869. }
  12870. };
  12871. // WebVR functions
  12872. /**
  12873. * Gets a boolean indicating if a webVR device was detected
  12874. * @returns true if a webVR device was detected
  12875. */
  12876. Engine.prototype.isVRDevicePresent = function () {
  12877. return !!this._vrDisplay;
  12878. };
  12879. /**
  12880. * Gets the current webVR device
  12881. * @returns the current webVR device (or null)
  12882. */
  12883. Engine.prototype.getVRDevice = function () {
  12884. return this._vrDisplay;
  12885. };
  12886. /**
  12887. * Initializes a webVR display and starts listening to display change events
  12888. * The onVRDisplayChangedObservable will be notified upon these changes
  12889. * @returns The onVRDisplayChangedObservable
  12890. */
  12891. Engine.prototype.initWebVR = function () {
  12892. this.initWebVRAsync();
  12893. return this.onVRDisplayChangedObservable;
  12894. };
  12895. /**
  12896. * Initializes a webVR display and starts listening to display change events
  12897. * The onVRDisplayChangedObservable will be notified upon these changes
  12898. * @returns A promise containing a VRDisplay and if vr is supported
  12899. */
  12900. Engine.prototype.initWebVRAsync = function () {
  12901. var _this = this;
  12902. var notifyObservers = function () {
  12903. var eventArgs = {
  12904. vrDisplay: _this._vrDisplay,
  12905. vrSupported: _this._vrSupported
  12906. };
  12907. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12908. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12909. };
  12910. if (!this._onVrDisplayConnect) {
  12911. this._onVrDisplayConnect = function (event) {
  12912. _this._vrDisplay = event.display;
  12913. notifyObservers();
  12914. };
  12915. this._onVrDisplayDisconnect = function () {
  12916. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12917. _this._vrDisplay = undefined;
  12918. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12919. notifyObservers();
  12920. };
  12921. this._onVrDisplayPresentChange = function () {
  12922. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12923. };
  12924. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12925. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12926. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12927. }
  12928. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12929. this._webVRInitPromise.then(notifyObservers);
  12930. return this._webVRInitPromise;
  12931. };
  12932. /**
  12933. * Call this function to switch to webVR mode
  12934. * Will do nothing if webVR is not supported or if there is no webVR device
  12935. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12936. */
  12937. Engine.prototype.enableVR = function () {
  12938. var _this = this;
  12939. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12940. var onResolved = function () {
  12941. _this.onVRRequestPresentComplete.notifyObservers(true);
  12942. _this._onVRFullScreenTriggered();
  12943. };
  12944. var onRejected = function () {
  12945. _this.onVRRequestPresentComplete.notifyObservers(false);
  12946. };
  12947. this.onVRRequestPresentStart.notifyObservers(this);
  12948. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12949. }
  12950. };
  12951. /**
  12952. * Call this function to leave webVR mode
  12953. * Will do nothing if webVR is not supported or if there is no webVR device
  12954. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12955. */
  12956. Engine.prototype.disableVR = function () {
  12957. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12958. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12959. }
  12960. };
  12961. Engine.prototype._getVRDisplaysAsync = function () {
  12962. var _this = this;
  12963. return new Promise(function (res, rej) {
  12964. if (navigator.getVRDisplays) {
  12965. navigator.getVRDisplays().then(function (devices) {
  12966. _this._vrSupported = true;
  12967. // note that devices may actually be an empty array. This is fine;
  12968. // we expect this._vrDisplay to be undefined in this case.
  12969. _this._vrDisplay = devices[0];
  12970. res({
  12971. vrDisplay: _this._vrDisplay,
  12972. vrSupported: _this._vrSupported
  12973. });
  12974. });
  12975. }
  12976. else {
  12977. _this._vrDisplay = undefined;
  12978. _this._vrSupported = false;
  12979. res({
  12980. vrDisplay: _this._vrDisplay,
  12981. vrSupported: _this._vrSupported
  12982. });
  12983. }
  12984. });
  12985. };
  12986. /**
  12987. * Binds the frame buffer to the specified texture.
  12988. * @param texture The texture to render to or null for the default canvas
  12989. * @param faceIndex The face of the texture to render to in case of cube texture
  12990. * @param requiredWidth The width of the target to render to
  12991. * @param requiredHeight The height of the target to render to
  12992. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12993. * @param depthStencilTexture The depth stencil texture to use to render
  12994. */
  12995. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12996. if (this._currentRenderTarget) {
  12997. this.unBindFramebuffer(this._currentRenderTarget);
  12998. }
  12999. this._currentRenderTarget = texture;
  13000. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13001. var gl = this._gl;
  13002. if (texture.isCube) {
  13003. if (faceIndex === undefined) {
  13004. faceIndex = 0;
  13005. }
  13006. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13007. if (depthStencilTexture) {
  13008. if (depthStencilTexture._generateStencilBuffer) {
  13009. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13010. }
  13011. else {
  13012. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13013. }
  13014. }
  13015. }
  13016. if (this._cachedViewport && !forceFullscreenViewport) {
  13017. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13018. }
  13019. else {
  13020. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  13021. }
  13022. this.wipeCaches();
  13023. };
  13024. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13025. if (this._currentFramebuffer !== framebuffer) {
  13026. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13027. this._currentFramebuffer = framebuffer;
  13028. }
  13029. };
  13030. /**
  13031. * Unbind the current render target texture from the webGL context
  13032. * @param texture defines the render target texture to unbind
  13033. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13034. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13035. */
  13036. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13037. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13038. this._currentRenderTarget = null;
  13039. // If MSAA, we need to bitblt back to main texture
  13040. var gl = this._gl;
  13041. if (texture._MSAAFramebuffer) {
  13042. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13043. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13044. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13045. }
  13046. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13047. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13048. gl.generateMipmap(gl.TEXTURE_2D);
  13049. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13050. }
  13051. if (onBeforeUnbind) {
  13052. if (texture._MSAAFramebuffer) {
  13053. // Bind the correct framebuffer
  13054. this.bindUnboundFramebuffer(texture._framebuffer);
  13055. }
  13056. onBeforeUnbind();
  13057. }
  13058. this.bindUnboundFramebuffer(null);
  13059. };
  13060. /**
  13061. * Unbind a list of render target textures from the webGL context
  13062. * This is used only when drawBuffer extension or webGL2 are active
  13063. * @param textures defines the render target textures to unbind
  13064. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13065. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13066. */
  13067. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13068. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13069. this._currentRenderTarget = null;
  13070. // If MSAA, we need to bitblt back to main texture
  13071. var gl = this._gl;
  13072. if (textures[0]._MSAAFramebuffer) {
  13073. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13074. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13075. var attachments = textures[0]._attachments;
  13076. if (!attachments) {
  13077. attachments = new Array(textures.length);
  13078. textures[0]._attachments = attachments;
  13079. }
  13080. for (var i = 0; i < textures.length; i++) {
  13081. var texture = textures[i];
  13082. for (var j = 0; j < attachments.length; j++) {
  13083. attachments[j] = gl.NONE;
  13084. }
  13085. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13086. gl.readBuffer(attachments[i]);
  13087. gl.drawBuffers(attachments);
  13088. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13089. }
  13090. for (var i = 0; i < attachments.length; i++) {
  13091. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13092. }
  13093. gl.drawBuffers(attachments);
  13094. }
  13095. for (var i = 0; i < textures.length; i++) {
  13096. var texture = textures[i];
  13097. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13098. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13099. gl.generateMipmap(gl.TEXTURE_2D);
  13100. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13101. }
  13102. }
  13103. if (onBeforeUnbind) {
  13104. if (textures[0]._MSAAFramebuffer) {
  13105. // Bind the correct framebuffer
  13106. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13107. }
  13108. onBeforeUnbind();
  13109. }
  13110. this.bindUnboundFramebuffer(null);
  13111. };
  13112. /**
  13113. * Force the mipmap generation for the given render target texture
  13114. * @param texture defines the render target texture to use
  13115. */
  13116. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13117. if (texture.generateMipMaps) {
  13118. var gl = this._gl;
  13119. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13120. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13121. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13122. }
  13123. };
  13124. /**
  13125. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13126. */
  13127. Engine.prototype.flushFramebuffer = function () {
  13128. this._gl.flush();
  13129. };
  13130. /**
  13131. * Unbind the current render target and bind the default framebuffer
  13132. */
  13133. Engine.prototype.restoreDefaultFramebuffer = function () {
  13134. if (this._currentRenderTarget) {
  13135. this.unBindFramebuffer(this._currentRenderTarget);
  13136. }
  13137. else {
  13138. this.bindUnboundFramebuffer(null);
  13139. }
  13140. if (this._cachedViewport) {
  13141. this.setViewport(this._cachedViewport);
  13142. }
  13143. this.wipeCaches();
  13144. };
  13145. // UBOs
  13146. /**
  13147. * Create an uniform buffer
  13148. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13149. * @param elements defines the content of the uniform buffer
  13150. * @returns the webGL uniform buffer
  13151. */
  13152. Engine.prototype.createUniformBuffer = function (elements) {
  13153. var ubo = this._gl.createBuffer();
  13154. if (!ubo) {
  13155. throw new Error("Unable to create uniform buffer");
  13156. }
  13157. this.bindUniformBuffer(ubo);
  13158. if (elements instanceof Float32Array) {
  13159. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13160. }
  13161. else {
  13162. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13163. }
  13164. this.bindUniformBuffer(null);
  13165. ubo.references = 1;
  13166. return ubo;
  13167. };
  13168. /**
  13169. * Create a dynamic uniform buffer
  13170. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13171. * @param elements defines the content of the uniform buffer
  13172. * @returns the webGL uniform buffer
  13173. */
  13174. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13175. var ubo = this._gl.createBuffer();
  13176. if (!ubo) {
  13177. throw new Error("Unable to create dynamic uniform buffer");
  13178. }
  13179. this.bindUniformBuffer(ubo);
  13180. if (elements instanceof Float32Array) {
  13181. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13182. }
  13183. else {
  13184. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13185. }
  13186. this.bindUniformBuffer(null);
  13187. ubo.references = 1;
  13188. return ubo;
  13189. };
  13190. /**
  13191. * Update an existing uniform buffer
  13192. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13193. * @param uniformBuffer defines the target uniform buffer
  13194. * @param elements defines the content to update
  13195. * @param offset defines the offset in the uniform buffer where update should start
  13196. * @param count defines the size of the data to update
  13197. */
  13198. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13199. this.bindUniformBuffer(uniformBuffer);
  13200. if (offset === undefined) {
  13201. offset = 0;
  13202. }
  13203. if (count === undefined) {
  13204. if (elements instanceof Float32Array) {
  13205. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13206. }
  13207. else {
  13208. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13209. }
  13210. }
  13211. else {
  13212. if (elements instanceof Float32Array) {
  13213. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13214. }
  13215. else {
  13216. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13217. }
  13218. }
  13219. this.bindUniformBuffer(null);
  13220. };
  13221. // VBOs
  13222. Engine.prototype._resetVertexBufferBinding = function () {
  13223. this.bindArrayBuffer(null);
  13224. this._cachedVertexBuffers = null;
  13225. };
  13226. /**
  13227. * Creates a vertex buffer
  13228. * @param data the data for the vertex buffer
  13229. * @returns the new WebGL static buffer
  13230. */
  13231. Engine.prototype.createVertexBuffer = function (data) {
  13232. var vbo = this._gl.createBuffer();
  13233. if (!vbo) {
  13234. throw new Error("Unable to create vertex buffer");
  13235. }
  13236. this.bindArrayBuffer(vbo);
  13237. if (data instanceof Array) {
  13238. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13239. }
  13240. else {
  13241. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13242. }
  13243. this._resetVertexBufferBinding();
  13244. vbo.references = 1;
  13245. return vbo;
  13246. };
  13247. /**
  13248. * Creates a dynamic vertex buffer
  13249. * @param data the data for the dynamic vertex buffer
  13250. * @returns the new WebGL dynamic buffer
  13251. */
  13252. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13253. var vbo = this._gl.createBuffer();
  13254. if (!vbo) {
  13255. throw new Error("Unable to create dynamic vertex buffer");
  13256. }
  13257. this.bindArrayBuffer(vbo);
  13258. if (data instanceof Array) {
  13259. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13260. }
  13261. else {
  13262. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13263. }
  13264. this._resetVertexBufferBinding();
  13265. vbo.references = 1;
  13266. return vbo;
  13267. };
  13268. /**
  13269. * Update a dynamic index buffer
  13270. * @param indexBuffer defines the target index buffer
  13271. * @param indices defines the data to update
  13272. * @param offset defines the offset in the target index buffer where update should start
  13273. */
  13274. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13275. if (offset === void 0) { offset = 0; }
  13276. // Force cache update
  13277. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13278. this.bindIndexBuffer(indexBuffer);
  13279. var arrayBuffer;
  13280. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13281. arrayBuffer = indices;
  13282. }
  13283. else {
  13284. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13285. }
  13286. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13287. this._resetIndexBufferBinding();
  13288. };
  13289. /**
  13290. * Updates a dynamic vertex buffer.
  13291. * @param vertexBuffer the vertex buffer to update
  13292. * @param data the data used to update the vertex buffer
  13293. * @param byteOffset the byte offset of the data
  13294. * @param byteLength the byte length of the data
  13295. */
  13296. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13297. this.bindArrayBuffer(vertexBuffer);
  13298. if (byteOffset === undefined) {
  13299. byteOffset = 0;
  13300. }
  13301. if (byteLength === undefined) {
  13302. if (data instanceof Array) {
  13303. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13304. }
  13305. else {
  13306. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13307. }
  13308. }
  13309. else {
  13310. if (data instanceof Array) {
  13311. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13312. }
  13313. else {
  13314. if (data instanceof ArrayBuffer) {
  13315. data = new Uint8Array(data, byteOffset, byteLength);
  13316. }
  13317. else {
  13318. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13319. }
  13320. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13321. }
  13322. }
  13323. this._resetVertexBufferBinding();
  13324. };
  13325. Engine.prototype._resetIndexBufferBinding = function () {
  13326. this.bindIndexBuffer(null);
  13327. this._cachedIndexBuffer = null;
  13328. };
  13329. /**
  13330. * Creates a new index buffer
  13331. * @param indices defines the content of the index buffer
  13332. * @param updatable defines if the index buffer must be updatable
  13333. * @returns a new webGL buffer
  13334. */
  13335. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13336. var vbo = this._gl.createBuffer();
  13337. if (!vbo) {
  13338. throw new Error("Unable to create index buffer");
  13339. }
  13340. this.bindIndexBuffer(vbo);
  13341. // Check for 32 bits indices
  13342. var arrayBuffer;
  13343. var need32Bits = false;
  13344. if (indices instanceof Uint16Array) {
  13345. arrayBuffer = indices;
  13346. }
  13347. else {
  13348. //check 32 bit support
  13349. if (this._caps.uintIndices) {
  13350. if (indices instanceof Uint32Array) {
  13351. arrayBuffer = indices;
  13352. need32Bits = true;
  13353. }
  13354. else {
  13355. //number[] or Int32Array, check if 32 bit is necessary
  13356. for (var index = 0; index < indices.length; index++) {
  13357. if (indices[index] > 65535) {
  13358. need32Bits = true;
  13359. break;
  13360. }
  13361. }
  13362. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13363. }
  13364. }
  13365. else {
  13366. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13367. arrayBuffer = new Uint16Array(indices);
  13368. }
  13369. }
  13370. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13371. this._resetIndexBufferBinding();
  13372. vbo.references = 1;
  13373. vbo.is32Bits = need32Bits;
  13374. return vbo;
  13375. };
  13376. /**
  13377. * Bind a webGL buffer to the webGL context
  13378. * @param buffer defines the buffer to bind
  13379. */
  13380. Engine.prototype.bindArrayBuffer = function (buffer) {
  13381. if (!this._vaoRecordInProgress) {
  13382. this._unbindVertexArrayObject();
  13383. }
  13384. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13385. };
  13386. /**
  13387. * Bind an uniform buffer to the current webGL context
  13388. * @param buffer defines the buffer to bind
  13389. */
  13390. Engine.prototype.bindUniformBuffer = function (buffer) {
  13391. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13392. };
  13393. /**
  13394. * Bind a buffer to the current webGL context at a given location
  13395. * @param buffer defines the buffer to bind
  13396. * @param location defines the index where to bind the buffer
  13397. */
  13398. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13399. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13400. };
  13401. /**
  13402. * Bind a specific block at a given index in a specific shader program
  13403. * @param shaderProgram defines the shader program
  13404. * @param blockName defines the block name
  13405. * @param index defines the index where to bind the block
  13406. */
  13407. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13408. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13409. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13410. };
  13411. ;
  13412. Engine.prototype.bindIndexBuffer = function (buffer) {
  13413. if (!this._vaoRecordInProgress) {
  13414. this._unbindVertexArrayObject();
  13415. }
  13416. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13417. };
  13418. Engine.prototype.bindBuffer = function (buffer, target) {
  13419. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13420. this._gl.bindBuffer(target, buffer);
  13421. this._currentBoundBuffer[target] = buffer;
  13422. }
  13423. };
  13424. /**
  13425. * update the bound buffer with the given data
  13426. * @param data defines the data to update
  13427. */
  13428. Engine.prototype.updateArrayBuffer = function (data) {
  13429. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13430. };
  13431. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13432. var pointer = this._currentBufferPointers[indx];
  13433. var changed = false;
  13434. if (!pointer.active) {
  13435. changed = true;
  13436. pointer.active = true;
  13437. pointer.index = indx;
  13438. pointer.size = size;
  13439. pointer.type = type;
  13440. pointer.normalized = normalized;
  13441. pointer.stride = stride;
  13442. pointer.offset = offset;
  13443. pointer.buffer = buffer;
  13444. }
  13445. else {
  13446. if (pointer.buffer !== buffer) {
  13447. pointer.buffer = buffer;
  13448. changed = true;
  13449. }
  13450. if (pointer.size !== size) {
  13451. pointer.size = size;
  13452. changed = true;
  13453. }
  13454. if (pointer.type !== type) {
  13455. pointer.type = type;
  13456. changed = true;
  13457. }
  13458. if (pointer.normalized !== normalized) {
  13459. pointer.normalized = normalized;
  13460. changed = true;
  13461. }
  13462. if (pointer.stride !== stride) {
  13463. pointer.stride = stride;
  13464. changed = true;
  13465. }
  13466. if (pointer.offset !== offset) {
  13467. pointer.offset = offset;
  13468. changed = true;
  13469. }
  13470. }
  13471. if (changed || this._vaoRecordInProgress) {
  13472. this.bindArrayBuffer(buffer);
  13473. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13474. }
  13475. };
  13476. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13477. if (indexBuffer == null) {
  13478. return;
  13479. }
  13480. if (this._cachedIndexBuffer !== indexBuffer) {
  13481. this._cachedIndexBuffer = indexBuffer;
  13482. this.bindIndexBuffer(indexBuffer);
  13483. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13484. }
  13485. };
  13486. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13487. var attributes = effect.getAttributesNames();
  13488. if (!this._vaoRecordInProgress) {
  13489. this._unbindVertexArrayObject();
  13490. }
  13491. this.unbindAllAttributes();
  13492. for (var index = 0; index < attributes.length; index++) {
  13493. var order = effect.getAttributeLocation(index);
  13494. if (order >= 0) {
  13495. var vertexBuffer = vertexBuffers[attributes[index]];
  13496. if (!vertexBuffer) {
  13497. continue;
  13498. }
  13499. this._gl.enableVertexAttribArray(order);
  13500. if (!this._vaoRecordInProgress) {
  13501. this._vertexAttribArraysEnabled[order] = true;
  13502. }
  13503. var buffer = vertexBuffer.getBuffer();
  13504. if (buffer) {
  13505. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13506. if (vertexBuffer.getIsInstanced()) {
  13507. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13508. if (!this._vaoRecordInProgress) {
  13509. this._currentInstanceLocations.push(order);
  13510. this._currentInstanceBuffers.push(buffer);
  13511. }
  13512. }
  13513. }
  13514. }
  13515. }
  13516. };
  13517. /**
  13518. * Records a vertex array object
  13519. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13520. * @param vertexBuffers defines the list of vertex buffers to store
  13521. * @param indexBuffer defines the index buffer to store
  13522. * @param effect defines the effect to store
  13523. * @returns the new vertex array object
  13524. */
  13525. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13526. var vao = this._gl.createVertexArray();
  13527. this._vaoRecordInProgress = true;
  13528. this._gl.bindVertexArray(vao);
  13529. this._mustWipeVertexAttributes = true;
  13530. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13531. this.bindIndexBuffer(indexBuffer);
  13532. this._vaoRecordInProgress = false;
  13533. this._gl.bindVertexArray(null);
  13534. return vao;
  13535. };
  13536. /**
  13537. * Bind a specific vertex array object
  13538. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13539. * @param vertexArrayObject defines the vertex array object to bind
  13540. * @param indexBuffer defines the index buffer to bind
  13541. */
  13542. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13543. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13544. this._cachedVertexArrayObject = vertexArrayObject;
  13545. this._gl.bindVertexArray(vertexArrayObject);
  13546. this._cachedVertexBuffers = null;
  13547. this._cachedIndexBuffer = null;
  13548. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13549. this._mustWipeVertexAttributes = true;
  13550. }
  13551. };
  13552. /**
  13553. * Bind webGl buffers directly to the webGL context
  13554. * @param vertexBuffer defines the vertex buffer to bind
  13555. * @param indexBuffer defines the index buffer to bind
  13556. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13557. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13558. * @param effect defines the effect associated with the vertex buffer
  13559. */
  13560. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13561. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13562. this._cachedVertexBuffers = vertexBuffer;
  13563. this._cachedEffectForVertexBuffers = effect;
  13564. var attributesCount = effect.getAttributesCount();
  13565. this._unbindVertexArrayObject();
  13566. this.unbindAllAttributes();
  13567. var offset = 0;
  13568. for (var index = 0; index < attributesCount; index++) {
  13569. if (index < vertexDeclaration.length) {
  13570. var order = effect.getAttributeLocation(index);
  13571. if (order >= 0) {
  13572. this._gl.enableVertexAttribArray(order);
  13573. this._vertexAttribArraysEnabled[order] = true;
  13574. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13575. }
  13576. offset += vertexDeclaration[index] * 4;
  13577. }
  13578. }
  13579. }
  13580. this._bindIndexBufferWithCache(indexBuffer);
  13581. };
  13582. Engine.prototype._unbindVertexArrayObject = function () {
  13583. if (!this._cachedVertexArrayObject) {
  13584. return;
  13585. }
  13586. this._cachedVertexArrayObject = null;
  13587. this._gl.bindVertexArray(null);
  13588. };
  13589. /**
  13590. * Bind a list of vertex buffers to the webGL context
  13591. * @param vertexBuffers defines the list of vertex buffers to bind
  13592. * @param indexBuffer defines the index buffer to bind
  13593. * @param effect defines the effect associated with the vertex buffers
  13594. */
  13595. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13596. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13597. this._cachedVertexBuffers = vertexBuffers;
  13598. this._cachedEffectForVertexBuffers = effect;
  13599. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13600. }
  13601. this._bindIndexBufferWithCache(indexBuffer);
  13602. };
  13603. /**
  13604. * Unbind all instance attributes
  13605. */
  13606. Engine.prototype.unbindInstanceAttributes = function () {
  13607. var boundBuffer;
  13608. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13609. var instancesBuffer = this._currentInstanceBuffers[i];
  13610. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13611. boundBuffer = instancesBuffer;
  13612. this.bindArrayBuffer(instancesBuffer);
  13613. }
  13614. var offsetLocation = this._currentInstanceLocations[i];
  13615. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13616. }
  13617. this._currentInstanceBuffers.length = 0;
  13618. this._currentInstanceLocations.length = 0;
  13619. };
  13620. /**
  13621. * Release and free the memory of a vertex array object
  13622. * @param vao defines the vertex array object to delete
  13623. */
  13624. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13625. this._gl.deleteVertexArray(vao);
  13626. };
  13627. /** @hidden */
  13628. Engine.prototype._releaseBuffer = function (buffer) {
  13629. buffer.references--;
  13630. if (buffer.references === 0) {
  13631. this._gl.deleteBuffer(buffer);
  13632. return true;
  13633. }
  13634. return false;
  13635. };
  13636. /**
  13637. * Creates a webGL buffer to use with instanciation
  13638. * @param capacity defines the size of the buffer
  13639. * @returns the webGL buffer
  13640. */
  13641. Engine.prototype.createInstancesBuffer = function (capacity) {
  13642. var buffer = this._gl.createBuffer();
  13643. if (!buffer) {
  13644. throw new Error("Unable to create instance buffer");
  13645. }
  13646. buffer.capacity = capacity;
  13647. this.bindArrayBuffer(buffer);
  13648. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13649. return buffer;
  13650. };
  13651. /**
  13652. * Delete a webGL buffer used with instanciation
  13653. * @param buffer defines the webGL buffer to delete
  13654. */
  13655. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13656. this._gl.deleteBuffer(buffer);
  13657. };
  13658. /**
  13659. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13660. * @param instancesBuffer defines the webGL buffer to update and bind
  13661. * @param data defines the data to store in the buffer
  13662. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13663. */
  13664. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13665. this.bindArrayBuffer(instancesBuffer);
  13666. if (data) {
  13667. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13668. }
  13669. if (offsetLocations[0].index !== undefined) {
  13670. var stride = 0;
  13671. for (var i = 0; i < offsetLocations.length; i++) {
  13672. var ai = offsetLocations[i];
  13673. stride += ai.attributeSize * 4;
  13674. }
  13675. for (var i = 0; i < offsetLocations.length; i++) {
  13676. var ai = offsetLocations[i];
  13677. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13678. this._gl.enableVertexAttribArray(ai.index);
  13679. this._vertexAttribArraysEnabled[ai.index] = true;
  13680. }
  13681. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13682. this._gl.vertexAttribDivisor(ai.index, 1);
  13683. this._currentInstanceLocations.push(ai.index);
  13684. this._currentInstanceBuffers.push(instancesBuffer);
  13685. }
  13686. }
  13687. else {
  13688. for (var index = 0; index < 4; index++) {
  13689. var offsetLocation = offsetLocations[index];
  13690. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13691. this._gl.enableVertexAttribArray(offsetLocation);
  13692. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13693. }
  13694. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13695. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13696. this._currentInstanceLocations.push(offsetLocation);
  13697. this._currentInstanceBuffers.push(instancesBuffer);
  13698. }
  13699. }
  13700. };
  13701. /**
  13702. * Apply all cached states (depth, culling, stencil and alpha)
  13703. */
  13704. Engine.prototype.applyStates = function () {
  13705. this._depthCullingState.apply(this._gl);
  13706. this._stencilState.apply(this._gl);
  13707. this._alphaState.apply(this._gl);
  13708. };
  13709. /**
  13710. * Send a draw order
  13711. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13712. * @param indexStart defines the starting index
  13713. * @param indexCount defines the number of index to draw
  13714. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13715. */
  13716. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13717. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13718. };
  13719. /**
  13720. * Draw a list of points
  13721. * @param verticesStart defines the index of first vertex to draw
  13722. * @param verticesCount defines the count of vertices to draw
  13723. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13724. */
  13725. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13726. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13727. };
  13728. /**
  13729. * Draw a list of unindexed primitives
  13730. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13731. * @param verticesStart defines the index of first vertex to draw
  13732. * @param verticesCount defines the count of vertices to draw
  13733. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13734. */
  13735. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13736. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13737. };
  13738. /**
  13739. * Draw a list of indexed primitives
  13740. * @param fillMode defines the primitive to use
  13741. * @param indexStart defines the starting index
  13742. * @param indexCount defines the number of index to draw
  13743. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13744. */
  13745. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13746. // Apply states
  13747. this.applyStates();
  13748. this._drawCalls.addCount(1, false);
  13749. // Render
  13750. var drawMode = this._drawMode(fillMode);
  13751. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13752. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13753. if (instancesCount) {
  13754. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13755. }
  13756. else {
  13757. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13758. }
  13759. };
  13760. /**
  13761. * Draw a list of unindexed primitives
  13762. * @param fillMode defines the primitive to use
  13763. * @param verticesStart defines the index of first vertex to draw
  13764. * @param verticesCount defines the count of vertices to draw
  13765. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13766. */
  13767. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13768. // Apply states
  13769. this.applyStates();
  13770. this._drawCalls.addCount(1, false);
  13771. var drawMode = this._drawMode(fillMode);
  13772. if (instancesCount) {
  13773. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13774. }
  13775. else {
  13776. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13777. }
  13778. };
  13779. Engine.prototype._drawMode = function (fillMode) {
  13780. switch (fillMode) {
  13781. // Triangle views
  13782. case BABYLON.Material.TriangleFillMode:
  13783. return this._gl.TRIANGLES;
  13784. case BABYLON.Material.PointFillMode:
  13785. return this._gl.POINTS;
  13786. case BABYLON.Material.WireFrameFillMode:
  13787. return this._gl.LINES;
  13788. // Draw modes
  13789. case BABYLON.Material.PointListDrawMode:
  13790. return this._gl.POINTS;
  13791. case BABYLON.Material.LineListDrawMode:
  13792. return this._gl.LINES;
  13793. case BABYLON.Material.LineLoopDrawMode:
  13794. return this._gl.LINE_LOOP;
  13795. case BABYLON.Material.LineStripDrawMode:
  13796. return this._gl.LINE_STRIP;
  13797. case BABYLON.Material.TriangleStripDrawMode:
  13798. return this._gl.TRIANGLE_STRIP;
  13799. case BABYLON.Material.TriangleFanDrawMode:
  13800. return this._gl.TRIANGLE_FAN;
  13801. default:
  13802. return this._gl.TRIANGLES;
  13803. }
  13804. };
  13805. // Shaders
  13806. /** @hidden */
  13807. Engine.prototype._releaseEffect = function (effect) {
  13808. if (this._compiledEffects[effect._key]) {
  13809. delete this._compiledEffects[effect._key];
  13810. this._deleteProgram(effect.getProgram());
  13811. }
  13812. };
  13813. /** @hidden */
  13814. Engine.prototype._deleteProgram = function (program) {
  13815. if (program) {
  13816. program.__SPECTOR_rebuildProgram = null;
  13817. if (program.transformFeedback) {
  13818. this.deleteTransformFeedback(program.transformFeedback);
  13819. program.transformFeedback = null;
  13820. }
  13821. this._gl.deleteProgram(program);
  13822. }
  13823. };
  13824. /**
  13825. * Create a new effect (used to store vertex/fragment shaders)
  13826. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13827. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13828. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13829. * @param samplers defines an array of string used to represent textures
  13830. * @param defines defines the string containing the defines to use to compile the shaders
  13831. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13832. * @param onCompiled defines a function to call when the effect creation is successful
  13833. * @param onError defines a function to call when the effect creation has failed
  13834. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13835. * @returns the new Effect
  13836. */
  13837. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13838. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13839. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13840. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13841. if (this._compiledEffects[name]) {
  13842. var compiledEffect = this._compiledEffects[name];
  13843. if (onCompiled && compiledEffect.isReady()) {
  13844. onCompiled(compiledEffect);
  13845. }
  13846. return compiledEffect;
  13847. }
  13848. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13849. effect._key = name;
  13850. this._compiledEffects[name] = effect;
  13851. return effect;
  13852. };
  13853. /**
  13854. * Create an effect to use with particle systems
  13855. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13856. * @param uniformsNames defines a list of attribute names
  13857. * @param samplers defines an array of string used to represent textures
  13858. * @param defines defines the string containing the defines to use to compile the shaders
  13859. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13860. * @param onCompiled defines a function to call when the effect creation is successful
  13861. * @param onError defines a function to call when the effect creation has failed
  13862. * @returns the new Effect
  13863. */
  13864. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13865. if (uniformsNames === void 0) { uniformsNames = []; }
  13866. if (samplers === void 0) { samplers = []; }
  13867. if (defines === void 0) { defines = ""; }
  13868. return this.createEffect({
  13869. vertex: "particles",
  13870. fragmentElement: fragmentName
  13871. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13872. };
  13873. /**
  13874. * Directly creates a webGL program
  13875. * @param vertexCode defines the vertex shader code to use
  13876. * @param fragmentCode defines the fragment shader code to use
  13877. * @param context defines the webGL context to use (if not set, the current one will be used)
  13878. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13879. * @returns the new webGL program
  13880. */
  13881. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13882. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13883. context = context || this._gl;
  13884. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13885. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13886. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13887. };
  13888. /**
  13889. * Creates a webGL program
  13890. * @param vertexCode defines the vertex shader code to use
  13891. * @param fragmentCode defines the fragment shader code to use
  13892. * @param defines defines the string containing the defines to use to compile the shaders
  13893. * @param context defines the webGL context to use (if not set, the current one will be used)
  13894. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13895. * @returns the new webGL program
  13896. */
  13897. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13898. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13899. context = context || this._gl;
  13900. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13901. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13902. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13903. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13904. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13905. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13906. return program;
  13907. };
  13908. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13909. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13910. var shaderProgram = context.createProgram();
  13911. if (!shaderProgram) {
  13912. throw new Error("Unable to create program");
  13913. }
  13914. context.attachShader(shaderProgram, vertexShader);
  13915. context.attachShader(shaderProgram, fragmentShader);
  13916. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13917. var transformFeedback = this.createTransformFeedback();
  13918. this.bindTransformFeedback(transformFeedback);
  13919. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13920. shaderProgram.transformFeedback = transformFeedback;
  13921. }
  13922. context.linkProgram(shaderProgram);
  13923. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13924. this.bindTransformFeedback(null);
  13925. }
  13926. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13927. if (!linked) {
  13928. context.validateProgram(shaderProgram);
  13929. var error = context.getProgramInfoLog(shaderProgram);
  13930. if (error) {
  13931. throw new Error(error);
  13932. }
  13933. }
  13934. context.deleteShader(vertexShader);
  13935. context.deleteShader(fragmentShader);
  13936. return shaderProgram;
  13937. };
  13938. /**
  13939. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13940. * @param shaderProgram defines the webGL program to use
  13941. * @param uniformsNames defines the list of uniform names
  13942. * @returns an array of webGL uniform locations
  13943. */
  13944. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13945. var results = new Array();
  13946. for (var index = 0; index < uniformsNames.length; index++) {
  13947. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13948. }
  13949. return results;
  13950. };
  13951. /**
  13952. * Gets the lsit of active attributes for a given webGL program
  13953. * @param shaderProgram defines the webGL program to use
  13954. * @param attributesNames defines the list of attribute names to get
  13955. * @returns an array of indices indicating the offset of each attribute
  13956. */
  13957. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13958. var results = [];
  13959. for (var index = 0; index < attributesNames.length; index++) {
  13960. try {
  13961. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13962. }
  13963. catch (e) {
  13964. results.push(-1);
  13965. }
  13966. }
  13967. return results;
  13968. };
  13969. /**
  13970. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13971. * @param effect defines the effect to activate
  13972. */
  13973. Engine.prototype.enableEffect = function (effect) {
  13974. if (!effect) {
  13975. return;
  13976. }
  13977. // Use program
  13978. this.bindSamplers(effect);
  13979. this._currentEffect = effect;
  13980. if (effect.onBind) {
  13981. effect.onBind(effect);
  13982. }
  13983. effect.onBindObservable.notifyObservers(effect);
  13984. };
  13985. /**
  13986. * Set the value of an uniform to an array of int32
  13987. * @param uniform defines the webGL uniform location where to store the value
  13988. * @param array defines the array of int32 to store
  13989. */
  13990. Engine.prototype.setIntArray = function (uniform, array) {
  13991. if (!uniform)
  13992. return;
  13993. this._gl.uniform1iv(uniform, array);
  13994. };
  13995. /**
  13996. * Set the value of an uniform to an array of int32 (stored as vec2)
  13997. * @param uniform defines the webGL uniform location where to store the value
  13998. * @param array defines the array of int32 to store
  13999. */
  14000. Engine.prototype.setIntArray2 = function (uniform, array) {
  14001. if (!uniform || array.length % 2 !== 0)
  14002. return;
  14003. this._gl.uniform2iv(uniform, array);
  14004. };
  14005. /**
  14006. * Set the value of an uniform to an array of int32 (stored as vec3)
  14007. * @param uniform defines the webGL uniform location where to store the value
  14008. * @param array defines the array of int32 to store
  14009. */
  14010. Engine.prototype.setIntArray3 = function (uniform, array) {
  14011. if (!uniform || array.length % 3 !== 0)
  14012. return;
  14013. this._gl.uniform3iv(uniform, array);
  14014. };
  14015. /**
  14016. * Set the value of an uniform to an array of int32 (stored as vec4)
  14017. * @param uniform defines the webGL uniform location where to store the value
  14018. * @param array defines the array of int32 to store
  14019. */
  14020. Engine.prototype.setIntArray4 = function (uniform, array) {
  14021. if (!uniform || array.length % 4 !== 0)
  14022. return;
  14023. this._gl.uniform4iv(uniform, array);
  14024. };
  14025. /**
  14026. * Set the value of an uniform to an array of float32
  14027. * @param uniform defines the webGL uniform location where to store the value
  14028. * @param array defines the array of float32 to store
  14029. */
  14030. Engine.prototype.setFloatArray = function (uniform, array) {
  14031. if (!uniform)
  14032. return;
  14033. this._gl.uniform1fv(uniform, array);
  14034. };
  14035. /**
  14036. * Set the value of an uniform to an array of float32 (stored as vec2)
  14037. * @param uniform defines the webGL uniform location where to store the value
  14038. * @param array defines the array of float32 to store
  14039. */
  14040. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14041. if (!uniform || array.length % 2 !== 0)
  14042. return;
  14043. this._gl.uniform2fv(uniform, array);
  14044. };
  14045. /**
  14046. * Set the value of an uniform to an array of float32 (stored as vec3)
  14047. * @param uniform defines the webGL uniform location where to store the value
  14048. * @param array defines the array of float32 to store
  14049. */
  14050. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14051. if (!uniform || array.length % 3 !== 0)
  14052. return;
  14053. this._gl.uniform3fv(uniform, array);
  14054. };
  14055. /**
  14056. * Set the value of an uniform to an array of float32 (stored as vec4)
  14057. * @param uniform defines the webGL uniform location where to store the value
  14058. * @param array defines the array of float32 to store
  14059. */
  14060. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14061. if (!uniform || array.length % 4 !== 0)
  14062. return;
  14063. this._gl.uniform4fv(uniform, array);
  14064. };
  14065. /**
  14066. * Set the value of an uniform to an array of number
  14067. * @param uniform defines the webGL uniform location where to store the value
  14068. * @param array defines the array of number to store
  14069. */
  14070. Engine.prototype.setArray = function (uniform, array) {
  14071. if (!uniform)
  14072. return;
  14073. this._gl.uniform1fv(uniform, array);
  14074. };
  14075. /**
  14076. * Set the value of an uniform to an array of number (stored as vec2)
  14077. * @param uniform defines the webGL uniform location where to store the value
  14078. * @param array defines the array of number to store
  14079. */
  14080. Engine.prototype.setArray2 = function (uniform, array) {
  14081. if (!uniform || array.length % 2 !== 0)
  14082. return;
  14083. this._gl.uniform2fv(uniform, array);
  14084. };
  14085. /**
  14086. * Set the value of an uniform to an array of number (stored as vec3)
  14087. * @param uniform defines the webGL uniform location where to store the value
  14088. * @param array defines the array of number to store
  14089. */
  14090. Engine.prototype.setArray3 = function (uniform, array) {
  14091. if (!uniform || array.length % 3 !== 0)
  14092. return;
  14093. this._gl.uniform3fv(uniform, array);
  14094. };
  14095. /**
  14096. * Set the value of an uniform to an array of number (stored as vec4)
  14097. * @param uniform defines the webGL uniform location where to store the value
  14098. * @param array defines the array of number to store
  14099. */
  14100. Engine.prototype.setArray4 = function (uniform, array) {
  14101. if (!uniform || array.length % 4 !== 0)
  14102. return;
  14103. this._gl.uniform4fv(uniform, array);
  14104. };
  14105. /**
  14106. * Set the value of an uniform to an array of float32 (stored as matrices)
  14107. * @param uniform defines the webGL uniform location where to store the value
  14108. * @param matrices defines the array of float32 to store
  14109. */
  14110. Engine.prototype.setMatrices = function (uniform, matrices) {
  14111. if (!uniform)
  14112. return;
  14113. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14114. };
  14115. /**
  14116. * Set the value of an uniform to a matrix
  14117. * @param uniform defines the webGL uniform location where to store the value
  14118. * @param matrix defines the matrix to store
  14119. */
  14120. Engine.prototype.setMatrix = function (uniform, matrix) {
  14121. if (!uniform)
  14122. return;
  14123. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14124. };
  14125. /**
  14126. * Set the value of an uniform to a matrix (3x3)
  14127. * @param uniform defines the webGL uniform location where to store the value
  14128. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14129. */
  14130. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14131. if (!uniform)
  14132. return;
  14133. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14134. };
  14135. /**
  14136. * Set the value of an uniform to a matrix (2x2)
  14137. * @param uniform defines the webGL uniform location where to store the value
  14138. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14139. */
  14140. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14141. if (!uniform)
  14142. return;
  14143. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14144. };
  14145. /**
  14146. * Set the value of an uniform to a number (int)
  14147. * @param uniform defines the webGL uniform location where to store the value
  14148. * @param value defines the int number to store
  14149. */
  14150. Engine.prototype.setInt = function (uniform, value) {
  14151. if (!uniform)
  14152. return;
  14153. this._gl.uniform1i(uniform, value);
  14154. };
  14155. /**
  14156. * Set the value of an uniform to a number (float)
  14157. * @param uniform defines the webGL uniform location where to store the value
  14158. * @param value defines the float number to store
  14159. */
  14160. Engine.prototype.setFloat = function (uniform, value) {
  14161. if (!uniform)
  14162. return;
  14163. this._gl.uniform1f(uniform, value);
  14164. };
  14165. /**
  14166. * Set the value of an uniform to a vec2
  14167. * @param uniform defines the webGL uniform location where to store the value
  14168. * @param x defines the 1st component of the value
  14169. * @param y defines the 2nd component of the value
  14170. */
  14171. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14172. if (!uniform)
  14173. return;
  14174. this._gl.uniform2f(uniform, x, y);
  14175. };
  14176. /**
  14177. * Set the value of an uniform to a vec3
  14178. * @param uniform defines the webGL uniform location where to store the value
  14179. * @param x defines the 1st component of the value
  14180. * @param y defines the 2nd component of the value
  14181. * @param z defines the 3rd component of the value
  14182. */
  14183. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14184. if (!uniform)
  14185. return;
  14186. this._gl.uniform3f(uniform, x, y, z);
  14187. };
  14188. /**
  14189. * Set the value of an uniform to a boolean
  14190. * @param uniform defines the webGL uniform location where to store the value
  14191. * @param bool defines the boolean to store
  14192. */
  14193. Engine.prototype.setBool = function (uniform, bool) {
  14194. if (!uniform)
  14195. return;
  14196. this._gl.uniform1i(uniform, bool);
  14197. };
  14198. /**
  14199. * Set the value of an uniform to a vec4
  14200. * @param uniform defines the webGL uniform location where to store the value
  14201. * @param x defines the 1st component of the value
  14202. * @param y defines the 2nd component of the value
  14203. * @param z defines the 3rd component of the value
  14204. * @param w defines the 4th component of the value
  14205. */
  14206. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14207. if (!uniform)
  14208. return;
  14209. this._gl.uniform4f(uniform, x, y, z, w);
  14210. };
  14211. /**
  14212. * Set the value of an uniform to a Color3
  14213. * @param uniform defines the webGL uniform location where to store the value
  14214. * @param color3 defines the color to store
  14215. */
  14216. Engine.prototype.setColor3 = function (uniform, color3) {
  14217. if (!uniform)
  14218. return;
  14219. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14220. };
  14221. /**
  14222. * Set the value of an uniform to a Color3 and an alpha value
  14223. * @param uniform defines the webGL uniform location where to store the value
  14224. * @param color3 defines the color to store
  14225. * @param alpha defines the alpha component to store
  14226. */
  14227. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14228. if (!uniform)
  14229. return;
  14230. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14231. };
  14232. /**
  14233. * Sets a Color4 on a uniform variable
  14234. * @param uniform defines the uniform location
  14235. * @param color4 defines the value to be set
  14236. */
  14237. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14238. if (!uniform)
  14239. return;
  14240. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14241. };
  14242. // States
  14243. /**
  14244. * Set various states to the webGL context
  14245. * @param culling defines backface culling state
  14246. * @param zOffset defines the value to apply to zOffset (0 by default)
  14247. * @param force defines if states must be applied even if cache is up to date
  14248. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14249. */
  14250. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14251. if (zOffset === void 0) { zOffset = 0; }
  14252. if (reverseSide === void 0) { reverseSide = false; }
  14253. // Culling
  14254. if (this._depthCullingState.cull !== culling || force) {
  14255. this._depthCullingState.cull = culling;
  14256. }
  14257. // Cull face
  14258. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14259. if (this._depthCullingState.cullFace !== cullFace || force) {
  14260. this._depthCullingState.cullFace = cullFace;
  14261. }
  14262. // Z offset
  14263. this.setZOffset(zOffset);
  14264. // Front face
  14265. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14266. if (this._depthCullingState.frontFace !== frontFace || force) {
  14267. this._depthCullingState.frontFace = frontFace;
  14268. }
  14269. };
  14270. /**
  14271. * Set the z offset to apply to current rendering
  14272. * @param value defines the offset to apply
  14273. */
  14274. Engine.prototype.setZOffset = function (value) {
  14275. this._depthCullingState.zOffset = value;
  14276. };
  14277. /**
  14278. * Gets the current value of the zOffset
  14279. * @returns the current zOffset state
  14280. */
  14281. Engine.prototype.getZOffset = function () {
  14282. return this._depthCullingState.zOffset;
  14283. };
  14284. /**
  14285. * Enable or disable depth buffering
  14286. * @param enable defines the state to set
  14287. */
  14288. Engine.prototype.setDepthBuffer = function (enable) {
  14289. this._depthCullingState.depthTest = enable;
  14290. };
  14291. /**
  14292. * Gets a boolean indicating if depth writing is enabled
  14293. * @returns the current depth writing state
  14294. */
  14295. Engine.prototype.getDepthWrite = function () {
  14296. return this._depthCullingState.depthMask;
  14297. };
  14298. /**
  14299. * Enable or disable depth writing
  14300. * @param enable defines the state to set
  14301. */
  14302. Engine.prototype.setDepthWrite = function (enable) {
  14303. this._depthCullingState.depthMask = enable;
  14304. };
  14305. /**
  14306. * Enable or disable color writing
  14307. * @param enable defines the state to set
  14308. */
  14309. Engine.prototype.setColorWrite = function (enable) {
  14310. this._gl.colorMask(enable, enable, enable, enable);
  14311. this._colorWrite = enable;
  14312. };
  14313. /**
  14314. * Gets a boolean indicating if color writing is enabled
  14315. * @returns the current color writing state
  14316. */
  14317. Engine.prototype.getColorWrite = function () {
  14318. return this._colorWrite;
  14319. };
  14320. /**
  14321. * Sets alpha constants used by some alpha blending modes
  14322. * @param r defines the red component
  14323. * @param g defines the green component
  14324. * @param b defines the blue component
  14325. * @param a defines the alpha component
  14326. */
  14327. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14328. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14329. };
  14330. /**
  14331. * Sets the current alpha mode
  14332. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14333. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14334. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14335. */
  14336. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14337. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14338. if (this._alphaMode === mode) {
  14339. return;
  14340. }
  14341. switch (mode) {
  14342. case Engine.ALPHA_DISABLE:
  14343. this._alphaState.alphaBlend = false;
  14344. break;
  14345. case Engine.ALPHA_PREMULTIPLIED:
  14346. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14347. this._alphaState.alphaBlend = true;
  14348. break;
  14349. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14350. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14351. this._alphaState.alphaBlend = true;
  14352. break;
  14353. case Engine.ALPHA_COMBINE:
  14354. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14355. this._alphaState.alphaBlend = true;
  14356. break;
  14357. case Engine.ALPHA_ONEONE:
  14358. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14359. this._alphaState.alphaBlend = true;
  14360. break;
  14361. case Engine.ALPHA_ADD:
  14362. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14363. this._alphaState.alphaBlend = true;
  14364. break;
  14365. case Engine.ALPHA_SUBTRACT:
  14366. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14367. this._alphaState.alphaBlend = true;
  14368. break;
  14369. case Engine.ALPHA_MULTIPLY:
  14370. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14371. this._alphaState.alphaBlend = true;
  14372. break;
  14373. case Engine.ALPHA_MAXIMIZED:
  14374. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14375. this._alphaState.alphaBlend = true;
  14376. break;
  14377. case Engine.ALPHA_INTERPOLATE:
  14378. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14379. this._alphaState.alphaBlend = true;
  14380. break;
  14381. case Engine.ALPHA_SCREENMODE:
  14382. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14383. this._alphaState.alphaBlend = true;
  14384. break;
  14385. }
  14386. if (!noDepthWriteChange) {
  14387. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14388. }
  14389. this._alphaMode = mode;
  14390. };
  14391. /**
  14392. * Gets the current alpha mode
  14393. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14394. * @returns the current alpha mode
  14395. */
  14396. Engine.prototype.getAlphaMode = function () {
  14397. return this._alphaMode;
  14398. };
  14399. // Textures
  14400. /**
  14401. * Force the entire cache to be cleared
  14402. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14403. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14404. */
  14405. Engine.prototype.wipeCaches = function (bruteForce) {
  14406. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14407. return;
  14408. }
  14409. this._currentEffect = null;
  14410. if (bruteForce) {
  14411. this.resetTextureCache();
  14412. this._currentProgram = null;
  14413. this._stencilState.reset();
  14414. this._depthCullingState.reset();
  14415. this.setDepthFunctionToLessOrEqual();
  14416. this._alphaState.reset();
  14417. }
  14418. this._resetVertexBufferBinding();
  14419. this._cachedIndexBuffer = null;
  14420. this._cachedEffectForVertexBuffers = null;
  14421. this._unbindVertexArrayObject();
  14422. this.bindIndexBuffer(null);
  14423. };
  14424. /**
  14425. * Set the compressed texture format to use, based on the formats you have, and the formats
  14426. * supported by the hardware / browser.
  14427. *
  14428. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14429. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14430. * to API arguments needed to compressed textures. This puts the burden on the container
  14431. * generator to house the arcane code for determining these for current & future formats.
  14432. *
  14433. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14434. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14435. *
  14436. * Note: The result of this call is not taken into account when a texture is base64.
  14437. *
  14438. * @param formatsAvailable defines the list of those format families you have created
  14439. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14440. *
  14441. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14442. * @returns The extension selected.
  14443. */
  14444. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14445. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14446. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14447. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14448. return this._textureFormatInUse = this._texturesSupported[i];
  14449. }
  14450. }
  14451. }
  14452. // actively set format to nothing, to allow this to be called more than once
  14453. // and possibly fail the 2nd time
  14454. this._textureFormatInUse = null;
  14455. return null;
  14456. };
  14457. /** @hidden */
  14458. Engine.prototype._createTexture = function () {
  14459. var texture = this._gl.createTexture();
  14460. if (!texture) {
  14461. throw new Error("Unable to create texture");
  14462. }
  14463. return texture;
  14464. };
  14465. /**
  14466. * Usually called from BABYLON.Texture.ts.
  14467. * Passed information to create a WebGLTexture
  14468. * @param urlArg defines a value which contains one of the following:
  14469. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14470. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14471. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14472. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14473. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14474. * @param scene needed for loading to the correct scene
  14475. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14476. * @param onLoad optional callback to be called upon successful completion
  14477. * @param onError optional callback to be called upon failure
  14478. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14479. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14480. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14481. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14482. */
  14483. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14484. var _this = this;
  14485. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14486. if (onLoad === void 0) { onLoad = null; }
  14487. if (onError === void 0) { onError = null; }
  14488. if (buffer === void 0) { buffer = null; }
  14489. if (fallback === void 0) { fallback = null; }
  14490. if (format === void 0) { format = null; }
  14491. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14492. var fromData = url.substr(0, 5) === "data:";
  14493. var fromBlob = url.substr(0, 5) === "blob:";
  14494. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14495. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14496. // establish the file extension, if possible
  14497. var lastDot = url.lastIndexOf('.');
  14498. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14499. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14500. var isTGA = (extension.indexOf(".tga") === 0);
  14501. // determine if a ktx file should be substituted
  14502. var isKTX = false;
  14503. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14504. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14505. isKTX = true;
  14506. }
  14507. if (scene) {
  14508. scene._addPendingData(texture);
  14509. }
  14510. texture.url = url;
  14511. texture.generateMipMaps = !noMipmap;
  14512. texture.samplingMode = samplingMode;
  14513. texture.invertY = invertY;
  14514. if (!this._doNotHandleContextLost) {
  14515. // Keep a link to the buffer only if we plan to handle context lost
  14516. texture._buffer = buffer;
  14517. }
  14518. var onLoadObserver = null;
  14519. if (onLoad && !fallback) {
  14520. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14521. }
  14522. if (!fallback)
  14523. this._internalTexturesCache.push(texture);
  14524. var onerror = function (message, exception) {
  14525. if (scene) {
  14526. scene._removePendingData(texture);
  14527. }
  14528. if (onLoadObserver) {
  14529. texture.onLoadedObservable.remove(onLoadObserver);
  14530. }
  14531. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14532. if (isKTX) {
  14533. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14534. }
  14535. else if (BABYLON.Tools.UseFallbackTexture) {
  14536. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14537. }
  14538. if (onError) {
  14539. onError(message || "Unknown error", exception);
  14540. }
  14541. };
  14542. var callback = null;
  14543. // processing for non-image formats
  14544. if (isKTX || isTGA || isDDS) {
  14545. if (isKTX) {
  14546. callback = function (data) {
  14547. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14548. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14549. ktx.uploadLevels(_this._gl, !noMipmap);
  14550. return false;
  14551. }, samplingMode);
  14552. };
  14553. }
  14554. else if (isTGA) {
  14555. callback = function (arrayBuffer) {
  14556. var data = new Uint8Array(arrayBuffer);
  14557. var header = BABYLON.TGATools.GetTGAHeader(data);
  14558. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14559. BABYLON.TGATools.UploadContent(_this._gl, data);
  14560. return false;
  14561. }, samplingMode);
  14562. };
  14563. }
  14564. else if (isDDS) {
  14565. callback = function (data) {
  14566. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14567. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14568. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14569. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14570. return false;
  14571. }, samplingMode);
  14572. };
  14573. }
  14574. if (!buffer) {
  14575. this._loadFile(url, function (data) {
  14576. if (callback) {
  14577. callback(data);
  14578. }
  14579. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14580. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14581. });
  14582. }
  14583. else {
  14584. if (callback) {
  14585. callback(buffer);
  14586. }
  14587. }
  14588. // image format processing
  14589. }
  14590. else {
  14591. var onload = function (img) {
  14592. if (fromBlob && !_this._doNotHandleContextLost) {
  14593. // We need to store the image if we need to rebuild the texture
  14594. // in case of a webgl context lost
  14595. texture._buffer = img;
  14596. }
  14597. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14598. var gl = _this._gl;
  14599. var isPot = (img.width === potWidth && img.height === potHeight);
  14600. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14601. if (isPot) {
  14602. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14603. return false;
  14604. }
  14605. // Using shaders to rescale because canvas.drawImage is lossy
  14606. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14607. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14608. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14609. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14610. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14611. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14612. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14613. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14614. _this._releaseTexture(source);
  14615. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14616. continuationCallback();
  14617. });
  14618. return true;
  14619. }, samplingMode);
  14620. };
  14621. if (!fromData || isBase64)
  14622. if (buffer instanceof HTMLImageElement) {
  14623. onload(buffer);
  14624. }
  14625. else {
  14626. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14627. }
  14628. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14629. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14630. else
  14631. onload(buffer);
  14632. }
  14633. return texture;
  14634. };
  14635. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14636. var _this = this;
  14637. var rtt = this.createRenderTargetTexture({
  14638. width: destination.width,
  14639. height: destination.height,
  14640. }, {
  14641. generateMipMaps: false,
  14642. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14643. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14644. generateDepthBuffer: false,
  14645. generateStencilBuffer: false
  14646. });
  14647. if (!this._rescalePostProcess) {
  14648. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14649. }
  14650. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14651. _this._rescalePostProcess.onApply = function (effect) {
  14652. effect._bindTexture("textureSampler", source);
  14653. };
  14654. var hostingScene = scene;
  14655. if (!hostingScene) {
  14656. hostingScene = _this.scenes[_this.scenes.length - 1];
  14657. }
  14658. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14659. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14660. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14661. _this.unBindFramebuffer(rtt);
  14662. _this._releaseTexture(rtt);
  14663. if (onComplete) {
  14664. onComplete();
  14665. }
  14666. });
  14667. };
  14668. /**
  14669. * Update a raw texture
  14670. * @param texture defines the texture to update
  14671. * @param data defines the data to store in the texture
  14672. * @param format defines the format of the data
  14673. * @param invertY defines if data must be stored with Y axis inverted
  14674. * @param compression defines the compression used (null by default)
  14675. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14676. */
  14677. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14678. if (compression === void 0) { compression = null; }
  14679. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14680. if (!texture) {
  14681. return;
  14682. }
  14683. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14684. var internalFormat = this._getInternalFormat(format);
  14685. var textureType = this._getWebGLTextureType(type);
  14686. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14687. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14688. if (!this._doNotHandleContextLost) {
  14689. texture._bufferView = data;
  14690. texture.format = format;
  14691. texture.type = type;
  14692. texture.invertY = invertY;
  14693. texture._compression = compression;
  14694. }
  14695. if (texture.width % 4 !== 0) {
  14696. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14697. }
  14698. if (compression && data) {
  14699. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14700. }
  14701. else {
  14702. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14703. }
  14704. if (texture.generateMipMaps) {
  14705. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14706. }
  14707. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14708. // this.resetTextureCache();
  14709. texture.isReady = true;
  14710. };
  14711. /**
  14712. * Creates a raw texture
  14713. * @param data defines the data to store in the texture
  14714. * @param width defines the width of the texture
  14715. * @param height defines the height of the texture
  14716. * @param format defines the format of the data
  14717. * @param generateMipMaps defines if the engine should generate the mip levels
  14718. * @param invertY defines if data must be stored with Y axis inverted
  14719. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14720. * @param compression defines the compression used (null by default)
  14721. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14722. * @returns the raw texture inside an InternalTexture
  14723. */
  14724. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14725. if (compression === void 0) { compression = null; }
  14726. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14727. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14728. texture.baseWidth = width;
  14729. texture.baseHeight = height;
  14730. texture.width = width;
  14731. texture.height = height;
  14732. texture.format = format;
  14733. texture.generateMipMaps = generateMipMaps;
  14734. texture.samplingMode = samplingMode;
  14735. texture.invertY = invertY;
  14736. texture._compression = compression;
  14737. texture.type = type;
  14738. if (!this._doNotHandleContextLost) {
  14739. texture._bufferView = data;
  14740. }
  14741. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14742. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14743. // Filters
  14744. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14745. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14746. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14747. if (generateMipMaps) {
  14748. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14749. }
  14750. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14751. this._internalTexturesCache.push(texture);
  14752. return texture;
  14753. };
  14754. /**
  14755. * Creates a dynamic texture
  14756. * @param width defines the width of the texture
  14757. * @param height defines the height of the texture
  14758. * @param generateMipMaps defines if the engine should generate the mip levels
  14759. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14760. * @returns the dynamic texture inside an InternalTexture
  14761. */
  14762. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14763. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14764. texture.baseWidth = width;
  14765. texture.baseHeight = height;
  14766. if (generateMipMaps) {
  14767. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14768. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14769. }
  14770. // this.resetTextureCache();
  14771. texture.width = width;
  14772. texture.height = height;
  14773. texture.isReady = false;
  14774. texture.generateMipMaps = generateMipMaps;
  14775. texture.samplingMode = samplingMode;
  14776. this.updateTextureSamplingMode(samplingMode, texture);
  14777. this._internalTexturesCache.push(texture);
  14778. return texture;
  14779. };
  14780. /**
  14781. * Update the sampling mode of a given texture
  14782. * @param samplingMode defines the required sampling mode
  14783. * @param texture defines the texture to update
  14784. */
  14785. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14786. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14787. if (texture.isCube) {
  14788. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14789. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14790. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14791. }
  14792. else if (texture.is3D) {
  14793. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14794. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14795. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14796. }
  14797. else {
  14798. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14799. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14800. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14801. }
  14802. texture.samplingMode = samplingMode;
  14803. };
  14804. /**
  14805. * Update the content of a dynamic texture
  14806. * @param texture defines the texture to update
  14807. * @param canvas defines the canvas containing the source
  14808. * @param invertY defines if data must be stored with Y axis inverted
  14809. * @param premulAlpha defines if alpha is stored as premultiplied
  14810. * @param format defines the format of the data
  14811. */
  14812. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14813. if (premulAlpha === void 0) { premulAlpha = false; }
  14814. if (!texture) {
  14815. return;
  14816. }
  14817. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14818. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14819. if (premulAlpha) {
  14820. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14821. }
  14822. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14823. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14824. if (texture.generateMipMaps) {
  14825. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14826. }
  14827. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14828. if (premulAlpha) {
  14829. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14830. }
  14831. texture.isReady = true;
  14832. };
  14833. /**
  14834. * Update a video texture
  14835. * @param texture defines the texture to update
  14836. * @param video defines the video element to use
  14837. * @param invertY defines if data must be stored with Y axis inverted
  14838. */
  14839. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14840. if (!texture || texture._isDisabled) {
  14841. return;
  14842. }
  14843. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14844. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14845. try {
  14846. // Testing video texture support
  14847. if (this._videoTextureSupported === undefined) {
  14848. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14849. if (this._gl.getError() !== 0) {
  14850. this._videoTextureSupported = false;
  14851. }
  14852. else {
  14853. this._videoTextureSupported = true;
  14854. }
  14855. }
  14856. // Copy video through the current working canvas if video texture is not supported
  14857. if (!this._videoTextureSupported) {
  14858. if (!texture._workingCanvas) {
  14859. texture._workingCanvas = document.createElement("canvas");
  14860. var context = texture._workingCanvas.getContext("2d");
  14861. if (!context) {
  14862. throw new Error("Unable to get 2d context");
  14863. }
  14864. texture._workingContext = context;
  14865. texture._workingCanvas.width = texture.width;
  14866. texture._workingCanvas.height = texture.height;
  14867. }
  14868. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14869. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14870. }
  14871. else {
  14872. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14873. }
  14874. if (texture.generateMipMaps) {
  14875. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14876. }
  14877. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14878. // this.resetTextureCache();
  14879. texture.isReady = true;
  14880. }
  14881. catch (ex) {
  14882. // Something unexpected
  14883. // Let's disable the texture
  14884. texture._isDisabled = true;
  14885. }
  14886. };
  14887. /**
  14888. * Updates a depth texture Comparison Mode and Function.
  14889. * If the comparison Function is equal to 0, the mode will be set to none.
  14890. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14891. * @param texture The texture to set the comparison function for
  14892. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14893. */
  14894. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14895. if (this.webGLVersion === 1) {
  14896. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14897. return;
  14898. }
  14899. var gl = this._gl;
  14900. if (texture.isCube) {
  14901. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14902. if (comparisonFunction === 0) {
  14903. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14904. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14905. }
  14906. else {
  14907. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14908. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14909. }
  14910. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14911. }
  14912. else {
  14913. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14914. if (comparisonFunction === 0) {
  14915. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14916. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14917. }
  14918. else {
  14919. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14920. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14921. }
  14922. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14923. }
  14924. texture._comparisonFunction = comparisonFunction;
  14925. };
  14926. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14927. var width = size.width || size;
  14928. var height = size.height || size;
  14929. internalTexture.baseWidth = width;
  14930. internalTexture.baseHeight = height;
  14931. internalTexture.width = width;
  14932. internalTexture.height = height;
  14933. internalTexture.isReady = true;
  14934. internalTexture.samples = 1;
  14935. internalTexture.generateMipMaps = false;
  14936. internalTexture._generateDepthBuffer = true;
  14937. internalTexture._generateStencilBuffer = generateStencil;
  14938. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14939. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14940. internalTexture._comparisonFunction = comparisonFunction;
  14941. var gl = this._gl;
  14942. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14943. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14944. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14945. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14946. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14947. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14948. if (comparisonFunction === 0) {
  14949. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14950. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14951. }
  14952. else {
  14953. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14954. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14955. }
  14956. };
  14957. /**
  14958. * Creates a depth stencil texture.
  14959. * This is only available in WebGL 2 or with the depth texture extension available.
  14960. * @param size The size of face edge in the texture.
  14961. * @param options The options defining the texture.
  14962. * @returns The texture
  14963. */
  14964. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14965. if (options.isCube) {
  14966. var width = size.width || size;
  14967. return this._createDepthStencilCubeTexture(width, options);
  14968. }
  14969. else {
  14970. return this._createDepthStencilTexture(size, options);
  14971. }
  14972. };
  14973. /**
  14974. * Creates a depth stencil texture.
  14975. * This is only available in WebGL 2 or with the depth texture extension available.
  14976. * @param size The size of face edge in the texture.
  14977. * @param options The options defining the texture.
  14978. * @returns The texture
  14979. */
  14980. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14981. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14982. if (!this._caps.depthTextureExtension) {
  14983. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14984. return internalTexture;
  14985. }
  14986. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14987. var gl = this._gl;
  14988. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14989. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14990. if (this.webGLVersion > 1) {
  14991. if (internalOptions.generateStencil) {
  14992. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14993. }
  14994. else {
  14995. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14996. }
  14997. }
  14998. else {
  14999. if (internalOptions.generateStencil) {
  15000. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15001. }
  15002. else {
  15003. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15004. }
  15005. }
  15006. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15007. return internalTexture;
  15008. };
  15009. /**
  15010. * Creates a depth stencil cube texture.
  15011. * This is only available in WebGL 2.
  15012. * @param size The size of face edge in the cube texture.
  15013. * @param options The options defining the cube texture.
  15014. * @returns The cube texture
  15015. */
  15016. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15017. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15018. internalTexture.isCube = true;
  15019. if (this.webGLVersion === 1) {
  15020. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15021. return internalTexture;
  15022. }
  15023. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15024. var gl = this._gl;
  15025. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15026. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15027. // Create the depth/stencil buffer
  15028. for (var face = 0; face < 6; face++) {
  15029. if (internalOptions.generateStencil) {
  15030. 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);
  15031. }
  15032. else {
  15033. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15034. }
  15035. }
  15036. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15037. return internalTexture;
  15038. };
  15039. /**
  15040. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15041. * @param renderTarget The render target to set the frame buffer for
  15042. */
  15043. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15044. // Create the framebuffer
  15045. var internalTexture = renderTarget.getInternalTexture();
  15046. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15047. return;
  15048. }
  15049. var gl = this._gl;
  15050. var depthStencilTexture = renderTarget.depthStencilTexture;
  15051. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15052. if (depthStencilTexture.isCube) {
  15053. if (depthStencilTexture._generateStencilBuffer) {
  15054. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15055. }
  15056. else {
  15057. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15058. }
  15059. }
  15060. else {
  15061. if (depthStencilTexture._generateStencilBuffer) {
  15062. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15063. }
  15064. else {
  15065. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15066. }
  15067. }
  15068. this.bindUnboundFramebuffer(null);
  15069. };
  15070. /**
  15071. * Creates a new render target texture
  15072. * @param size defines the size of the texture
  15073. * @param options defines the options used to create the texture
  15074. * @returns a new render target texture stored in an InternalTexture
  15075. */
  15076. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15077. var fullOptions = new RenderTargetCreationOptions();
  15078. if (options !== undefined && typeof options === "object") {
  15079. fullOptions.generateMipMaps = options.generateMipMaps;
  15080. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15081. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15082. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15083. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15084. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15085. }
  15086. else {
  15087. fullOptions.generateMipMaps = options;
  15088. fullOptions.generateDepthBuffer = true;
  15089. fullOptions.generateStencilBuffer = false;
  15090. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15091. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15092. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15093. }
  15094. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15095. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15096. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15097. }
  15098. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15099. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15100. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15101. }
  15102. var gl = this._gl;
  15103. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15104. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15105. var width = size.width || size;
  15106. var height = size.height || size;
  15107. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15108. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15109. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15110. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15111. }
  15112. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15113. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15114. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15115. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15116. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15117. // Create the framebuffer
  15118. var framebuffer = gl.createFramebuffer();
  15119. this.bindUnboundFramebuffer(framebuffer);
  15120. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15121. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15122. if (fullOptions.generateMipMaps) {
  15123. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15124. }
  15125. // Unbind
  15126. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15127. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15128. this.bindUnboundFramebuffer(null);
  15129. texture._framebuffer = framebuffer;
  15130. texture.baseWidth = width;
  15131. texture.baseHeight = height;
  15132. texture.width = width;
  15133. texture.height = height;
  15134. texture.isReady = true;
  15135. texture.samples = 1;
  15136. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15137. texture.samplingMode = fullOptions.samplingMode;
  15138. texture.type = fullOptions.type;
  15139. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15140. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15141. // this.resetTextureCache();
  15142. this._internalTexturesCache.push(texture);
  15143. return texture;
  15144. };
  15145. /**
  15146. * Create a multi render target texture
  15147. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15148. * @param size defines the size of the texture
  15149. * @param options defines the creation options
  15150. * @returns the cube texture as an InternalTexture
  15151. */
  15152. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15153. var generateMipMaps = false;
  15154. var generateDepthBuffer = true;
  15155. var generateStencilBuffer = false;
  15156. var generateDepthTexture = false;
  15157. var textureCount = 1;
  15158. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15159. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15160. var types = new Array();
  15161. var samplingModes = new Array();
  15162. if (options !== undefined) {
  15163. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15164. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15165. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15166. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15167. textureCount = options.textureCount || 1;
  15168. if (options.types) {
  15169. types = options.types;
  15170. }
  15171. if (options.samplingModes) {
  15172. samplingModes = options.samplingModes;
  15173. }
  15174. }
  15175. var gl = this._gl;
  15176. // Create the framebuffer
  15177. var framebuffer = gl.createFramebuffer();
  15178. this.bindUnboundFramebuffer(framebuffer);
  15179. var width = size.width || size;
  15180. var height = size.height || size;
  15181. var textures = [];
  15182. var attachments = [];
  15183. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15184. for (var i = 0; i < textureCount; i++) {
  15185. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15186. var type = types[i] || defaultType;
  15187. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15188. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15189. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15190. }
  15191. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15192. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15193. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15194. }
  15195. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15196. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15197. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15198. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15199. }
  15200. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15201. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15202. textures.push(texture);
  15203. attachments.push(attachment);
  15204. gl.activeTexture(gl["TEXTURE" + i]);
  15205. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15206. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15207. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15208. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15209. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15210. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15211. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15212. if (generateMipMaps) {
  15213. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15214. }
  15215. // Unbind
  15216. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15217. texture._framebuffer = framebuffer;
  15218. texture._depthStencilBuffer = depthStencilBuffer;
  15219. texture.baseWidth = width;
  15220. texture.baseHeight = height;
  15221. texture.width = width;
  15222. texture.height = height;
  15223. texture.isReady = true;
  15224. texture.samples = 1;
  15225. texture.generateMipMaps = generateMipMaps;
  15226. texture.samplingMode = samplingMode;
  15227. texture.type = type;
  15228. texture._generateDepthBuffer = generateDepthBuffer;
  15229. texture._generateStencilBuffer = generateStencilBuffer;
  15230. texture._attachments = attachments;
  15231. this._internalTexturesCache.push(texture);
  15232. }
  15233. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15234. // Depth texture
  15235. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15236. gl.activeTexture(gl.TEXTURE0);
  15237. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15238. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15239. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15240. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15241. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15242. 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);
  15243. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15244. depthTexture._framebuffer = framebuffer;
  15245. depthTexture.baseWidth = width;
  15246. depthTexture.baseHeight = height;
  15247. depthTexture.width = width;
  15248. depthTexture.height = height;
  15249. depthTexture.isReady = true;
  15250. depthTexture.samples = 1;
  15251. depthTexture.generateMipMaps = generateMipMaps;
  15252. depthTexture.samplingMode = gl.NEAREST;
  15253. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15254. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15255. textures.push(depthTexture);
  15256. this._internalTexturesCache.push(depthTexture);
  15257. }
  15258. gl.drawBuffers(attachments);
  15259. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15260. this.bindUnboundFramebuffer(null);
  15261. this.resetTextureCache();
  15262. return textures;
  15263. };
  15264. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15265. if (samples === void 0) { samples = 1; }
  15266. var depthStencilBuffer = null;
  15267. var gl = this._gl;
  15268. // Create the depth/stencil buffer
  15269. if (generateStencilBuffer) {
  15270. depthStencilBuffer = gl.createRenderbuffer();
  15271. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15272. if (samples > 1) {
  15273. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15274. }
  15275. else {
  15276. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15277. }
  15278. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15279. }
  15280. else if (generateDepthBuffer) {
  15281. depthStencilBuffer = gl.createRenderbuffer();
  15282. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15283. if (samples > 1) {
  15284. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15285. }
  15286. else {
  15287. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15288. }
  15289. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15290. }
  15291. return depthStencilBuffer;
  15292. };
  15293. /**
  15294. * Updates the sample count of a render target texture
  15295. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15296. * @param texture defines the texture to update
  15297. * @param samples defines the sample count to set
  15298. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15299. */
  15300. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15301. if (this.webGLVersion < 2 || !texture) {
  15302. return 1;
  15303. }
  15304. if (texture.samples === samples) {
  15305. return samples;
  15306. }
  15307. var gl = this._gl;
  15308. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15309. // Dispose previous render buffers
  15310. if (texture._depthStencilBuffer) {
  15311. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15312. texture._depthStencilBuffer = null;
  15313. }
  15314. if (texture._MSAAFramebuffer) {
  15315. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15316. texture._MSAAFramebuffer = null;
  15317. }
  15318. if (texture._MSAARenderBuffer) {
  15319. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15320. texture._MSAARenderBuffer = null;
  15321. }
  15322. if (samples > 1) {
  15323. var framebuffer = gl.createFramebuffer();
  15324. if (!framebuffer) {
  15325. throw new Error("Unable to create multi sampled framebuffer");
  15326. }
  15327. texture._MSAAFramebuffer = framebuffer;
  15328. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15329. var colorRenderbuffer = gl.createRenderbuffer();
  15330. if (!colorRenderbuffer) {
  15331. throw new Error("Unable to create multi sampled framebuffer");
  15332. }
  15333. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15334. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15335. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15336. texture._MSAARenderBuffer = colorRenderbuffer;
  15337. }
  15338. else {
  15339. this.bindUnboundFramebuffer(texture._framebuffer);
  15340. }
  15341. texture.samples = samples;
  15342. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15343. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15344. this.bindUnboundFramebuffer(null);
  15345. return samples;
  15346. };
  15347. /**
  15348. * Update the sample count for a given multiple render target texture
  15349. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15350. * @param textures defines the textures to update
  15351. * @param samples defines the sample count to set
  15352. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15353. */
  15354. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15355. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15356. return 1;
  15357. }
  15358. if (textures[0].samples === samples) {
  15359. return samples;
  15360. }
  15361. var gl = this._gl;
  15362. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15363. // Dispose previous render buffers
  15364. if (textures[0]._depthStencilBuffer) {
  15365. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15366. textures[0]._depthStencilBuffer = null;
  15367. }
  15368. if (textures[0]._MSAAFramebuffer) {
  15369. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15370. textures[0]._MSAAFramebuffer = null;
  15371. }
  15372. for (var i = 0; i < textures.length; i++) {
  15373. if (textures[i]._MSAARenderBuffer) {
  15374. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15375. textures[i]._MSAARenderBuffer = null;
  15376. }
  15377. }
  15378. if (samples > 1) {
  15379. var framebuffer = gl.createFramebuffer();
  15380. if (!framebuffer) {
  15381. throw new Error("Unable to create multi sampled framebuffer");
  15382. }
  15383. this.bindUnboundFramebuffer(framebuffer);
  15384. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15385. var attachments = [];
  15386. for (var i = 0; i < textures.length; i++) {
  15387. var texture = textures[i];
  15388. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15389. var colorRenderbuffer = gl.createRenderbuffer();
  15390. if (!colorRenderbuffer) {
  15391. throw new Error("Unable to create multi sampled framebuffer");
  15392. }
  15393. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15394. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15395. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15396. texture._MSAAFramebuffer = framebuffer;
  15397. texture._MSAARenderBuffer = colorRenderbuffer;
  15398. texture.samples = samples;
  15399. texture._depthStencilBuffer = depthStencilBuffer;
  15400. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15401. attachments.push(attachment);
  15402. }
  15403. gl.drawBuffers(attachments);
  15404. }
  15405. else {
  15406. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15407. }
  15408. this.bindUnboundFramebuffer(null);
  15409. return samples;
  15410. };
  15411. /** @hidden */
  15412. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15413. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15414. };
  15415. /** @hidden */
  15416. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15417. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15418. };
  15419. /**
  15420. * Creates a new render target cube texture
  15421. * @param size defines the size of the texture
  15422. * @param options defines the options used to create the texture
  15423. * @returns a new render target cube texture stored in an InternalTexture
  15424. */
  15425. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15426. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15427. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15428. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15429. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15430. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15431. }
  15432. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15433. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15434. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15435. }
  15436. var gl = this._gl;
  15437. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15438. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15439. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15440. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15441. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15442. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15443. }
  15444. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15445. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15446. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15447. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15448. for (var face = 0; face < 6; face++) {
  15449. 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);
  15450. }
  15451. // Create the framebuffer
  15452. var framebuffer = gl.createFramebuffer();
  15453. this.bindUnboundFramebuffer(framebuffer);
  15454. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15455. // MipMaps
  15456. if (fullOptions.generateMipMaps) {
  15457. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15458. }
  15459. // Unbind
  15460. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15461. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15462. this.bindUnboundFramebuffer(null);
  15463. texture._framebuffer = framebuffer;
  15464. texture.width = size;
  15465. texture.height = size;
  15466. texture.isReady = true;
  15467. texture.isCube = true;
  15468. texture.samples = 1;
  15469. texture.generateMipMaps = fullOptions.generateMipMaps;
  15470. texture.samplingMode = fullOptions.samplingMode;
  15471. texture.type = fullOptions.type;
  15472. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15473. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15474. this._internalTexturesCache.push(texture);
  15475. return texture;
  15476. };
  15477. /**
  15478. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15479. * @param rootUrl defines the url where the file to load is located
  15480. * @param scene defines the current scene
  15481. * @param scale defines scale to apply to the mip map selection
  15482. * @param offset defines offset to apply to the mip map selection
  15483. * @param onLoad defines an optional callback raised when the texture is loaded
  15484. * @param onError defines an optional callback raised if there is an issue to load the texture
  15485. * @param format defines the format of the data
  15486. * @param forcedExtension defines the extension to use to pick the right loader
  15487. * @returns the cube texture as an InternalTexture
  15488. */
  15489. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15490. var _this = this;
  15491. if (onLoad === void 0) { onLoad = null; }
  15492. if (onError === void 0) { onError = null; }
  15493. if (forcedExtension === void 0) { forcedExtension = null; }
  15494. var callback = function (loadData) {
  15495. if (!loadData) {
  15496. if (onLoad) {
  15497. onLoad(null);
  15498. }
  15499. return;
  15500. }
  15501. var texture = loadData.texture;
  15502. if (loadData.info.sphericalPolynomial) {
  15503. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15504. }
  15505. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15506. texture._lodGenerationScale = scale;
  15507. texture._lodGenerationOffset = offset;
  15508. if (_this._caps.textureLOD) {
  15509. // Do not add extra process if texture lod is supported.
  15510. if (onLoad) {
  15511. onLoad(texture);
  15512. }
  15513. return;
  15514. }
  15515. var mipSlices = 3;
  15516. var gl = _this._gl;
  15517. var width = loadData.width;
  15518. if (!width) {
  15519. return;
  15520. }
  15521. var textures = [];
  15522. for (var i = 0; i < mipSlices; i++) {
  15523. //compute LOD from even spacing in smoothness (matching shader calculation)
  15524. var smoothness = i / (mipSlices - 1);
  15525. var roughness = 1 - smoothness;
  15526. var minLODIndex = offset; // roughness = 0
  15527. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15528. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15529. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15530. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15531. glTextureFromLod.isCube = true;
  15532. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15533. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15534. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15535. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15536. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15537. if (loadData.isDDS) {
  15538. var info = loadData.info;
  15539. var data = loadData.data;
  15540. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15541. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15542. }
  15543. else {
  15544. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15545. }
  15546. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15547. // Wrap in a base texture for easy binding.
  15548. var lodTexture = new BABYLON.BaseTexture(scene);
  15549. lodTexture.isCube = true;
  15550. lodTexture._texture = glTextureFromLod;
  15551. glTextureFromLod.isReady = true;
  15552. textures.push(lodTexture);
  15553. }
  15554. texture._lodTextureHigh = textures[2];
  15555. texture._lodTextureMid = textures[1];
  15556. texture._lodTextureLow = textures[0];
  15557. if (onLoad) {
  15558. onLoad(texture);
  15559. }
  15560. };
  15561. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, true);
  15562. };
  15563. /**
  15564. * Creates a cube texture
  15565. * @param rootUrl defines the url where the files to load is located
  15566. * @param scene defines the current scene
  15567. * @param files defines the list of files to load (1 per face)
  15568. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15569. * @param onLoad defines an optional callback raised when the texture is loaded
  15570. * @param onError defines an optional callback raised if there is an issue to load the texture
  15571. * @param format defines the format of the data
  15572. * @param forcedExtension defines the extension to use to pick the right loader
  15573. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15574. * @returns the cube texture as an InternalTexture
  15575. */
  15576. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15577. var _this = this;
  15578. if (onLoad === void 0) { onLoad = null; }
  15579. if (onError === void 0) { onError = null; }
  15580. if (forcedExtension === void 0) { forcedExtension = null; }
  15581. if (createPolynomials === void 0) { createPolynomials = false; }
  15582. var gl = this._gl;
  15583. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15584. texture.isCube = true;
  15585. texture.url = rootUrl;
  15586. texture.generateMipMaps = !noMipmap;
  15587. if (!this._doNotHandleContextLost) {
  15588. texture._extension = forcedExtension;
  15589. texture._files = files;
  15590. }
  15591. var isKTX = false;
  15592. var isDDS = false;
  15593. var lastDot = rootUrl.lastIndexOf('.');
  15594. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15595. if (this._textureFormatInUse) {
  15596. extension = this._textureFormatInUse;
  15597. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15598. isKTX = true;
  15599. }
  15600. else {
  15601. isDDS = (extension === ".dds");
  15602. }
  15603. var onerror = function (request, exception) {
  15604. if (onError && request) {
  15605. onError(request.status + " " + request.statusText, exception);
  15606. }
  15607. };
  15608. if (isKTX) {
  15609. this._loadFile(rootUrl, function (data) {
  15610. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15611. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15612. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15613. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15614. ktx.uploadLevels(_this._gl, !noMipmap);
  15615. _this.setCubeMapTextureParams(gl, loadMipmap);
  15616. texture.width = ktx.pixelWidth;
  15617. texture.height = ktx.pixelHeight;
  15618. texture.isReady = true;
  15619. }, undefined, undefined, true, onerror);
  15620. }
  15621. else if (isDDS) {
  15622. if (files && files.length === 6) {
  15623. this._cascadeLoadFiles(scene, function (imgs) {
  15624. var info;
  15625. var loadMipmap = false;
  15626. var width = 0;
  15627. for (var index = 0; index < imgs.length; index++) {
  15628. var data = imgs[index];
  15629. info = BABYLON.DDSTools.GetDDSInfo(data);
  15630. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15631. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15632. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15633. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15634. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15635. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15636. }
  15637. texture.width = info.width;
  15638. texture.height = info.height;
  15639. texture.type = info.textureType;
  15640. width = info.width;
  15641. }
  15642. _this.setCubeMapTextureParams(gl, loadMipmap);
  15643. texture.isReady = true;
  15644. if (onLoad) {
  15645. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15646. }
  15647. }, files, onError);
  15648. }
  15649. else {
  15650. this._loadFile(rootUrl, function (data) {
  15651. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15652. if (createPolynomials) {
  15653. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15654. }
  15655. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15656. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15657. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15658. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15659. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15660. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15661. }
  15662. _this.setCubeMapTextureParams(gl, loadMipmap);
  15663. texture.width = info.width;
  15664. texture.height = info.height;
  15665. texture.isReady = true;
  15666. texture.type = info.textureType;
  15667. if (onLoad) {
  15668. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15669. }
  15670. }, undefined, undefined, true, onerror);
  15671. }
  15672. }
  15673. else {
  15674. if (!files) {
  15675. throw new Error("Cannot load cubemap because files were not defined");
  15676. }
  15677. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15678. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15679. var height = width;
  15680. _this._prepareWorkingCanvas();
  15681. if (!_this._workingCanvas || !_this._workingContext) {
  15682. return;
  15683. }
  15684. _this._workingCanvas.width = width;
  15685. _this._workingCanvas.height = height;
  15686. var faces = [
  15687. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15688. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15689. ];
  15690. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15691. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15692. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15693. for (var index = 0; index < faces.length; index++) {
  15694. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15695. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15696. }
  15697. if (!noMipmap) {
  15698. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15699. }
  15700. _this.setCubeMapTextureParams(gl, !noMipmap);
  15701. texture.width = width;
  15702. texture.height = height;
  15703. texture.isReady = true;
  15704. if (format) {
  15705. texture.format = format;
  15706. }
  15707. texture.onLoadedObservable.notifyObservers(texture);
  15708. texture.onLoadedObservable.clear();
  15709. if (onLoad) {
  15710. onLoad();
  15711. }
  15712. }, files, onError);
  15713. }
  15714. this._internalTexturesCache.push(texture);
  15715. return texture;
  15716. };
  15717. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15718. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15719. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15720. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15721. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15722. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15723. // this.resetTextureCache();
  15724. };
  15725. /**
  15726. * Update a raw cube texture
  15727. * @param texture defines the texture to udpdate
  15728. * @param data defines the data to store
  15729. * @param format defines the data format
  15730. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15731. * @param invertY defines if data must be stored with Y axis inverted
  15732. * @param compression defines the compression used (null by default)
  15733. * @param level defines which level of the texture to update
  15734. */
  15735. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15736. if (compression === void 0) { compression = null; }
  15737. if (level === void 0) { level = 0; }
  15738. texture._bufferViewArray = data;
  15739. texture.format = format;
  15740. texture.type = type;
  15741. texture.invertY = invertY;
  15742. texture._compression = compression;
  15743. var gl = this._gl;
  15744. var textureType = this._getWebGLTextureType(type);
  15745. var internalFormat = this._getInternalFormat(format);
  15746. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15747. var needConversion = false;
  15748. if (internalFormat === gl.RGB) {
  15749. internalFormat = gl.RGBA;
  15750. needConversion = true;
  15751. }
  15752. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15753. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15754. if (texture.width % 4 !== 0) {
  15755. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15756. }
  15757. // Data are known to be in +X +Y +Z -X -Y -Z
  15758. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15759. var faceData = data[faceIndex];
  15760. if (compression) {
  15761. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15762. }
  15763. else {
  15764. if (needConversion) {
  15765. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15766. }
  15767. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15768. }
  15769. }
  15770. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15771. if (isPot && texture.generateMipMaps && level === 0) {
  15772. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15773. }
  15774. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15775. // this.resetTextureCache();
  15776. texture.isReady = true;
  15777. };
  15778. /**
  15779. * Creates a new raw cube texture
  15780. * @param data defines the array of data to use to create each face
  15781. * @param size defines the size of the textures
  15782. * @param format defines the format of the data
  15783. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15784. * @param generateMipMaps defines if the engine should generate the mip levels
  15785. * @param invertY defines if data must be stored with Y axis inverted
  15786. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15787. * @param compression defines the compression used (null by default)
  15788. * @returns the cube texture as an InternalTexture
  15789. */
  15790. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15791. if (compression === void 0) { compression = null; }
  15792. var gl = this._gl;
  15793. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15794. texture.isCube = true;
  15795. texture.generateMipMaps = generateMipMaps;
  15796. texture.format = format;
  15797. texture.type = type;
  15798. if (!this._doNotHandleContextLost) {
  15799. texture._bufferViewArray = data;
  15800. }
  15801. var textureType = this._getWebGLTextureType(type);
  15802. var internalFormat = this._getInternalFormat(format);
  15803. if (internalFormat === gl.RGB) {
  15804. internalFormat = gl.RGBA;
  15805. }
  15806. var width = size;
  15807. var height = width;
  15808. texture.width = width;
  15809. texture.height = height;
  15810. // Double check on POT to generate Mips.
  15811. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15812. if (!isPot) {
  15813. generateMipMaps = false;
  15814. }
  15815. // Upload data if needed. The texture won't be ready until then.
  15816. if (data) {
  15817. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15818. }
  15819. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15820. // Filters
  15821. if (data && generateMipMaps) {
  15822. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15823. }
  15824. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15825. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15826. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15827. }
  15828. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15829. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15830. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15831. }
  15832. else {
  15833. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15834. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15835. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15836. }
  15837. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15838. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15839. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15840. return texture;
  15841. };
  15842. /**
  15843. * Creates a new raw cube texture from a specified url
  15844. * @param url defines the url where the data is located
  15845. * @param scene defines the current scene
  15846. * @param size defines the size of the textures
  15847. * @param format defines the format of the data
  15848. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15849. * @param noMipmap defines if the engine should avoid generating the mip levels
  15850. * @param callback defines a callback used to extract texture data from loaded data
  15851. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15852. * @param onLoad defines a callback called when texture is loaded
  15853. * @param onError defines a callback called if there is an error
  15854. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15855. * @param invertY defines if data must be stored with Y axis inverted
  15856. * @returns the cube texture as an InternalTexture
  15857. */
  15858. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15859. var _this = this;
  15860. if (onLoad === void 0) { onLoad = null; }
  15861. if (onError === void 0) { onError = null; }
  15862. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15863. if (invertY === void 0) { invertY = false; }
  15864. var gl = this._gl;
  15865. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15866. scene._addPendingData(texture);
  15867. texture.url = url;
  15868. this._internalTexturesCache.push(texture);
  15869. var onerror = function (request, exception) {
  15870. scene._removePendingData(texture);
  15871. if (onError && request) {
  15872. onError(request.status + " " + request.statusText, exception);
  15873. }
  15874. };
  15875. var internalCallback = function (data) {
  15876. var width = texture.width;
  15877. var faceDataArrays = callback(data);
  15878. if (!faceDataArrays) {
  15879. return;
  15880. }
  15881. if (mipmapGenerator) {
  15882. var textureType = _this._getWebGLTextureType(type);
  15883. var internalFormat = _this._getInternalFormat(format);
  15884. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15885. var needConversion = false;
  15886. if (internalFormat === gl.RGB) {
  15887. internalFormat = gl.RGBA;
  15888. needConversion = true;
  15889. }
  15890. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15891. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15892. var mipData = mipmapGenerator(faceDataArrays);
  15893. for (var level = 0; level < mipData.length; level++) {
  15894. var mipSize = width >> level;
  15895. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15896. var mipFaceData = mipData[level][faceIndex];
  15897. if (needConversion) {
  15898. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15899. }
  15900. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15901. }
  15902. }
  15903. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15904. }
  15905. else {
  15906. texture.generateMipMaps = !noMipmap;
  15907. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15908. }
  15909. texture.isReady = true;
  15910. // this.resetTextureCache();
  15911. scene._removePendingData(texture);
  15912. if (onLoad) {
  15913. onLoad();
  15914. }
  15915. };
  15916. this._loadFile(url, function (data) {
  15917. internalCallback(data);
  15918. }, undefined, scene.database, true, onerror);
  15919. return texture;
  15920. };
  15921. ;
  15922. /**
  15923. * Update a raw 3D texture
  15924. * @param texture defines the texture to update
  15925. * @param data defines the data to store
  15926. * @param format defines the data format
  15927. * @param invertY defines if data must be stored with Y axis inverted
  15928. * @param compression defines the used compression (can be null)
  15929. */
  15930. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15931. if (compression === void 0) { compression = null; }
  15932. var internalFormat = this._getInternalFormat(format);
  15933. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15934. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15935. if (!this._doNotHandleContextLost) {
  15936. texture._bufferView = data;
  15937. texture.format = format;
  15938. texture.invertY = invertY;
  15939. texture._compression = compression;
  15940. }
  15941. if (texture.width % 4 !== 0) {
  15942. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15943. }
  15944. if (compression && data) {
  15945. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15946. }
  15947. else {
  15948. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15949. }
  15950. if (texture.generateMipMaps) {
  15951. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15952. }
  15953. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15954. // this.resetTextureCache();
  15955. texture.isReady = true;
  15956. };
  15957. /**
  15958. * Creates a new raw 3D texture
  15959. * @param data defines the data used to create the texture
  15960. * @param width defines the width of the texture
  15961. * @param height defines the height of the texture
  15962. * @param depth defines the depth of the texture
  15963. * @param format defines the format of the texture
  15964. * @param generateMipMaps defines if the engine must generate mip levels
  15965. * @param invertY defines if data must be stored with Y axis inverted
  15966. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15967. * @param compression defines the compressed used (can be null)
  15968. * @returns a new raw 3D texture (stored in an InternalTexture)
  15969. */
  15970. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15971. if (compression === void 0) { compression = null; }
  15972. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15973. texture.baseWidth = width;
  15974. texture.baseHeight = height;
  15975. texture.baseDepth = depth;
  15976. texture.width = width;
  15977. texture.height = height;
  15978. texture.depth = depth;
  15979. texture.format = format;
  15980. texture.generateMipMaps = generateMipMaps;
  15981. texture.samplingMode = samplingMode;
  15982. texture.is3D = true;
  15983. if (!this._doNotHandleContextLost) {
  15984. texture._bufferView = data;
  15985. }
  15986. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15987. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15988. // Filters
  15989. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15990. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15991. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15992. if (generateMipMaps) {
  15993. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15994. }
  15995. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15996. this._internalTexturesCache.push(texture);
  15997. return texture;
  15998. };
  15999. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16000. var gl = this._gl;
  16001. if (!gl) {
  16002. return;
  16003. }
  16004. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16005. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16006. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16007. if (!noMipmap && !isCompressed) {
  16008. gl.generateMipmap(gl.TEXTURE_2D);
  16009. }
  16010. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16011. // this.resetTextureCache();
  16012. if (scene) {
  16013. scene._removePendingData(texture);
  16014. }
  16015. texture.onLoadedObservable.notifyObservers(texture);
  16016. texture.onLoadedObservable.clear();
  16017. };
  16018. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16019. var _this = this;
  16020. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16021. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16022. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16023. var gl = this._gl;
  16024. if (!gl) {
  16025. return;
  16026. }
  16027. if (!texture._webGLTexture) {
  16028. // this.resetTextureCache();
  16029. if (scene) {
  16030. scene._removePendingData(texture);
  16031. }
  16032. return;
  16033. }
  16034. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16035. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16036. texture.baseWidth = width;
  16037. texture.baseHeight = height;
  16038. texture.width = potWidth;
  16039. texture.height = potHeight;
  16040. texture.isReady = true;
  16041. if (processFunction(potWidth, potHeight, function () {
  16042. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16043. })) {
  16044. // Returning as texture needs extra async steps
  16045. return;
  16046. }
  16047. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16048. };
  16049. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16050. // Create new RGBA data container.
  16051. var rgbaData;
  16052. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16053. rgbaData = new Float32Array(width * height * 4);
  16054. }
  16055. else {
  16056. rgbaData = new Uint32Array(width * height * 4);
  16057. }
  16058. // Convert each pixel.
  16059. for (var x = 0; x < width; x++) {
  16060. for (var y = 0; y < height; y++) {
  16061. var index = (y * width + x) * 3;
  16062. var newIndex = (y * width + x) * 4;
  16063. // Map Old Value to new value.
  16064. rgbaData[newIndex + 0] = rgbData[index + 0];
  16065. rgbaData[newIndex + 1] = rgbData[index + 1];
  16066. rgbaData[newIndex + 2] = rgbData[index + 2];
  16067. // Add fully opaque alpha channel.
  16068. rgbaData[newIndex + 3] = 1;
  16069. }
  16070. }
  16071. return rgbaData;
  16072. };
  16073. /** @hidden */
  16074. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16075. var gl = this._gl;
  16076. if (texture._framebuffer) {
  16077. gl.deleteFramebuffer(texture._framebuffer);
  16078. texture._framebuffer = null;
  16079. }
  16080. if (texture._depthStencilBuffer) {
  16081. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16082. texture._depthStencilBuffer = null;
  16083. }
  16084. if (texture._MSAAFramebuffer) {
  16085. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16086. texture._MSAAFramebuffer = null;
  16087. }
  16088. if (texture._MSAARenderBuffer) {
  16089. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16090. texture._MSAARenderBuffer = null;
  16091. }
  16092. };
  16093. /** @hidden */
  16094. Engine.prototype._releaseTexture = function (texture) {
  16095. var gl = this._gl;
  16096. this._releaseFramebufferObjects(texture);
  16097. gl.deleteTexture(texture._webGLTexture);
  16098. // Unbind channels
  16099. this.unbindAllTextures();
  16100. var index = this._internalTexturesCache.indexOf(texture);
  16101. if (index !== -1) {
  16102. this._internalTexturesCache.splice(index, 1);
  16103. }
  16104. // Integrated fixed lod samplers.
  16105. if (texture._lodTextureHigh) {
  16106. texture._lodTextureHigh.dispose();
  16107. }
  16108. if (texture._lodTextureMid) {
  16109. texture._lodTextureMid.dispose();
  16110. }
  16111. if (texture._lodTextureLow) {
  16112. texture._lodTextureLow.dispose();
  16113. }
  16114. // Set output texture of post process to null if the texture has been released/disposed
  16115. this.scenes.forEach(function (scene) {
  16116. scene.postProcesses.forEach(function (postProcess) {
  16117. if (postProcess._outputTexture == texture) {
  16118. postProcess._outputTexture = null;
  16119. }
  16120. });
  16121. scene.cameras.forEach(function (camera) {
  16122. camera._postProcesses.forEach(function (postProcess) {
  16123. if (postProcess) {
  16124. if (postProcess._outputTexture == texture) {
  16125. postProcess._outputTexture = null;
  16126. }
  16127. }
  16128. });
  16129. });
  16130. });
  16131. };
  16132. Engine.prototype.setProgram = function (program) {
  16133. if (this._currentProgram !== program) {
  16134. this._gl.useProgram(program);
  16135. this._currentProgram = program;
  16136. }
  16137. };
  16138. /**
  16139. * Binds an effect to the webGL context
  16140. * @param effect defines the effect to bind
  16141. */
  16142. Engine.prototype.bindSamplers = function (effect) {
  16143. this.setProgram(effect.getProgram());
  16144. var samplers = effect.getSamplers();
  16145. for (var index = 0; index < samplers.length; index++) {
  16146. var uniform = effect.getUniform(samplers[index]);
  16147. if (uniform) {
  16148. this._boundUniforms[index] = uniform;
  16149. }
  16150. }
  16151. this._currentEffect = null;
  16152. };
  16153. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16154. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16155. return;
  16156. }
  16157. // Remove
  16158. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16159. // Bind last to it
  16160. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16161. // Bind to dummy
  16162. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16163. };
  16164. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16165. if (!internalTexture) {
  16166. return -1;
  16167. }
  16168. internalTexture._initialSlot = channel;
  16169. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16170. if (channel !== internalTexture._designatedSlot) {
  16171. this._textureCollisions.addCount(1, false);
  16172. }
  16173. }
  16174. else {
  16175. if (channel !== internalTexture._designatedSlot) {
  16176. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16177. return internalTexture._designatedSlot;
  16178. }
  16179. else {
  16180. // No slot for this texture, let's pick a new one (if we find a free slot)
  16181. if (this._nextFreeTextureSlots.length) {
  16182. return this._nextFreeTextureSlots[0];
  16183. }
  16184. // We need to recycle the oldest bound texture, sorry.
  16185. this._textureCollisions.addCount(1, false);
  16186. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16187. }
  16188. }
  16189. }
  16190. return channel;
  16191. };
  16192. Engine.prototype._linkTrackers = function (previous, next) {
  16193. previous.next = next;
  16194. next.previous = previous;
  16195. };
  16196. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16197. var currentSlot = internalTexture._designatedSlot;
  16198. if (currentSlot === -1) {
  16199. return -1;
  16200. }
  16201. internalTexture._designatedSlot = -1;
  16202. if (this.disableTextureBindingOptimization) {
  16203. return -1;
  16204. }
  16205. // Remove from bound list
  16206. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16207. // Free the slot
  16208. this._boundTexturesCache[currentSlot] = null;
  16209. this._nextFreeTextureSlots.push(currentSlot);
  16210. return currentSlot;
  16211. };
  16212. Engine.prototype._activateCurrentTexture = function () {
  16213. if (this._currentTextureChannel !== this._activeChannel) {
  16214. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16215. this._currentTextureChannel = this._activeChannel;
  16216. }
  16217. };
  16218. /** @hidden */
  16219. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16220. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16221. if (force === void 0) { force = false; }
  16222. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16223. this._activeChannel = texture._designatedSlot;
  16224. }
  16225. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16226. var isTextureForRendering = texture && texture._initialSlot > -1;
  16227. if (currentTextureBound !== texture || force) {
  16228. if (currentTextureBound) {
  16229. this._removeDesignatedSlot(currentTextureBound);
  16230. }
  16231. this._activateCurrentTexture();
  16232. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16233. this._boundTexturesCache[this._activeChannel] = texture;
  16234. if (texture) {
  16235. if (!this.disableTextureBindingOptimization) {
  16236. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16237. if (slotIndex > -1) {
  16238. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16239. }
  16240. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16241. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16242. }
  16243. texture._designatedSlot = this._activeChannel;
  16244. }
  16245. }
  16246. else if (forTextureDataUpdate) {
  16247. this._activateCurrentTexture();
  16248. }
  16249. if (isTextureForRendering && !forTextureDataUpdate) {
  16250. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16251. }
  16252. };
  16253. /** @hidden */
  16254. Engine.prototype._bindTexture = function (channel, texture) {
  16255. if (channel < 0) {
  16256. return;
  16257. }
  16258. if (texture) {
  16259. channel = this._getCorrectTextureChannel(channel, texture);
  16260. }
  16261. this._activeChannel = channel;
  16262. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16263. };
  16264. /**
  16265. * Sets a texture to the webGL context from a postprocess
  16266. * @param channel defines the channel to use
  16267. * @param postProcess defines the source postprocess
  16268. */
  16269. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16270. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16271. };
  16272. /**
  16273. * Binds the output of the passed in post process to the texture channel specified
  16274. * @param channel The channel the texture should be bound to
  16275. * @param postProcess The post process which's output should be bound
  16276. */
  16277. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16278. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16279. };
  16280. /**
  16281. * Unbind all textures from the webGL context
  16282. */
  16283. Engine.prototype.unbindAllTextures = function () {
  16284. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16285. this._activeChannel = channel;
  16286. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16287. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16288. if (this.webGLVersion > 1) {
  16289. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16290. }
  16291. }
  16292. };
  16293. /**
  16294. * Sets a texture to the according uniform.
  16295. * @param channel The texture channel
  16296. * @param uniform The uniform to set
  16297. * @param texture The texture to apply
  16298. */
  16299. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16300. if (channel < 0) {
  16301. return;
  16302. }
  16303. if (uniform) {
  16304. this._boundUniforms[channel] = uniform;
  16305. }
  16306. this._setTexture(channel, texture);
  16307. };
  16308. /**
  16309. * Sets a depth stencil texture from a render target to the according uniform.
  16310. * @param channel The texture channel
  16311. * @param uniform The uniform to set
  16312. * @param texture The render target texture containing the depth stencil texture to apply
  16313. */
  16314. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16315. if (channel < 0) {
  16316. return;
  16317. }
  16318. if (uniform) {
  16319. this._boundUniforms[channel] = uniform;
  16320. }
  16321. if (!texture || !texture.depthStencilTexture) {
  16322. this._setTexture(channel, null);
  16323. }
  16324. else {
  16325. this._setTexture(channel, texture, false, true);
  16326. }
  16327. };
  16328. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16329. var uniform = this._boundUniforms[sourceSlot];
  16330. if (uniform._currentState === destination) {
  16331. return;
  16332. }
  16333. this._gl.uniform1i(uniform, destination);
  16334. uniform._currentState = destination;
  16335. };
  16336. Engine.prototype._getTextureWrapMode = function (mode) {
  16337. switch (mode) {
  16338. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16339. return this._gl.REPEAT;
  16340. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16341. return this._gl.CLAMP_TO_EDGE;
  16342. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16343. return this._gl.MIRRORED_REPEAT;
  16344. }
  16345. return this._gl.REPEAT;
  16346. };
  16347. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16348. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16349. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16350. // Not ready?
  16351. if (!texture) {
  16352. if (this._boundTexturesCache[channel] != null) {
  16353. this._activeChannel = channel;
  16354. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16355. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16356. if (this.webGLVersion > 1) {
  16357. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16358. }
  16359. }
  16360. return false;
  16361. }
  16362. // Video
  16363. if (texture.video) {
  16364. this._activeChannel = channel;
  16365. texture.update();
  16366. }
  16367. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16368. texture.delayLoad();
  16369. return false;
  16370. }
  16371. var internalTexture;
  16372. if (depthStencilTexture) {
  16373. internalTexture = texture.depthStencilTexture;
  16374. }
  16375. else if (texture.isReady()) {
  16376. internalTexture = texture.getInternalTexture();
  16377. }
  16378. else if (texture.isCube) {
  16379. internalTexture = this.emptyCubeTexture;
  16380. }
  16381. else if (texture.is3D) {
  16382. internalTexture = this.emptyTexture3D;
  16383. }
  16384. else {
  16385. internalTexture = this.emptyTexture;
  16386. }
  16387. if (!isPartOfTextureArray) {
  16388. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16389. }
  16390. var needToBind = true;
  16391. if (this._boundTexturesCache[channel] === internalTexture) {
  16392. this._moveBoundTextureOnTop(internalTexture);
  16393. if (!isPartOfTextureArray) {
  16394. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16395. }
  16396. needToBind = false;
  16397. }
  16398. this._activeChannel = channel;
  16399. if (internalTexture && internalTexture.is3D) {
  16400. if (needToBind) {
  16401. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16402. }
  16403. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16404. internalTexture._cachedWrapU = texture.wrapU;
  16405. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16406. }
  16407. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16408. internalTexture._cachedWrapV = texture.wrapV;
  16409. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16410. }
  16411. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16412. internalTexture._cachedWrapR = texture.wrapR;
  16413. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16414. }
  16415. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16416. }
  16417. else if (internalTexture && internalTexture.isCube) {
  16418. if (needToBind) {
  16419. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16420. }
  16421. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16422. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16423. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16424. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16425. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16426. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16427. }
  16428. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16429. }
  16430. else {
  16431. if (needToBind) {
  16432. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16433. }
  16434. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16435. internalTexture._cachedWrapU = texture.wrapU;
  16436. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16437. }
  16438. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16439. internalTexture._cachedWrapV = texture.wrapV;
  16440. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16441. }
  16442. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16443. }
  16444. return true;
  16445. };
  16446. /**
  16447. * Sets an array of texture to the webGL context
  16448. * @param channel defines the channel where the texture array must be set
  16449. * @param uniform defines the associated uniform location
  16450. * @param textures defines the array of textures to bind
  16451. */
  16452. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16453. if (channel < 0 || !uniform) {
  16454. return;
  16455. }
  16456. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16457. this._textureUnits = new Int32Array(textures.length);
  16458. }
  16459. for (var i = 0; i < textures.length; i++) {
  16460. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16461. }
  16462. this._gl.uniform1iv(uniform, this._textureUnits);
  16463. for (var index = 0; index < textures.length; index++) {
  16464. this._setTexture(this._textureUnits[index], textures[index], true);
  16465. }
  16466. };
  16467. /** @hidden */
  16468. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16469. var internalTexture = texture.getInternalTexture();
  16470. if (!internalTexture) {
  16471. return;
  16472. }
  16473. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16474. var value = texture.anisotropicFilteringLevel;
  16475. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16476. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16477. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16478. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16479. }
  16480. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16481. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16482. internalTexture._cachedAnisotropicFilteringLevel = value;
  16483. }
  16484. };
  16485. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16486. this._bindTextureDirectly(target, texture, true, true);
  16487. this._gl.texParameterf(target, parameter, value);
  16488. };
  16489. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16490. if (texture) {
  16491. this._bindTextureDirectly(target, texture, true, true);
  16492. }
  16493. this._gl.texParameteri(target, parameter, value);
  16494. };
  16495. /**
  16496. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16497. * @param x defines the x coordinate of the rectangle where pixels must be read
  16498. * @param y defines the y coordinate of the rectangle where pixels must be read
  16499. * @param width defines the width of the rectangle where pixels must be read
  16500. * @param height defines the height of the rectangle where pixels must be read
  16501. * @returns a Uint8Array containing RGBA colors
  16502. */
  16503. Engine.prototype.readPixels = function (x, y, width, height) {
  16504. var data = new Uint8Array(height * width * 4);
  16505. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16506. return data;
  16507. };
  16508. /**
  16509. * Add an externaly attached data from its key.
  16510. * This method call will fail and return false, if such key already exists.
  16511. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16512. * @param key the unique key that identifies the data
  16513. * @param data the data object to associate to the key for this Engine instance
  16514. * @return true if no such key were already present and the data was added successfully, false otherwise
  16515. */
  16516. Engine.prototype.addExternalData = function (key, data) {
  16517. if (!this._externalData) {
  16518. this._externalData = new BABYLON.StringDictionary();
  16519. }
  16520. return this._externalData.add(key, data);
  16521. };
  16522. /**
  16523. * Get an externaly attached data from its key
  16524. * @param key the unique key that identifies the data
  16525. * @return the associated data, if present (can be null), or undefined if not present
  16526. */
  16527. Engine.prototype.getExternalData = function (key) {
  16528. if (!this._externalData) {
  16529. this._externalData = new BABYLON.StringDictionary();
  16530. }
  16531. return this._externalData.get(key);
  16532. };
  16533. /**
  16534. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16535. * @param key the unique key that identifies the data
  16536. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16537. * @return the associated data, can be null if the factory returned null.
  16538. */
  16539. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16540. if (!this._externalData) {
  16541. this._externalData = new BABYLON.StringDictionary();
  16542. }
  16543. return this._externalData.getOrAddWithFactory(key, factory);
  16544. };
  16545. /**
  16546. * Remove an externaly attached data from the Engine instance
  16547. * @param key the unique key that identifies the data
  16548. * @return true if the data was successfully removed, false if it doesn't exist
  16549. */
  16550. Engine.prototype.removeExternalData = function (key) {
  16551. if (!this._externalData) {
  16552. this._externalData = new BABYLON.StringDictionary();
  16553. }
  16554. return this._externalData.remove(key);
  16555. };
  16556. /**
  16557. * Unbind all vertex attributes from the webGL context
  16558. */
  16559. Engine.prototype.unbindAllAttributes = function () {
  16560. if (this._mustWipeVertexAttributes) {
  16561. this._mustWipeVertexAttributes = false;
  16562. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16563. this._gl.disableVertexAttribArray(i);
  16564. this._vertexAttribArraysEnabled[i] = false;
  16565. this._currentBufferPointers[i].active = false;
  16566. }
  16567. return;
  16568. }
  16569. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16570. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16571. continue;
  16572. }
  16573. this._gl.disableVertexAttribArray(i);
  16574. this._vertexAttribArraysEnabled[i] = false;
  16575. this._currentBufferPointers[i].active = false;
  16576. }
  16577. };
  16578. /**
  16579. * 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
  16580. */
  16581. Engine.prototype.releaseEffects = function () {
  16582. for (var name in this._compiledEffects) {
  16583. this._deleteProgram(this._compiledEffects[name]._program);
  16584. }
  16585. this._compiledEffects = {};
  16586. };
  16587. /**
  16588. * Dispose and release all associated resources
  16589. */
  16590. Engine.prototype.dispose = function () {
  16591. this.hideLoadingUI();
  16592. this.stopRenderLoop();
  16593. // Release postProcesses
  16594. while (this.postProcesses.length) {
  16595. this.postProcesses[0].dispose();
  16596. }
  16597. // Empty texture
  16598. if (this._emptyTexture) {
  16599. this._releaseTexture(this._emptyTexture);
  16600. this._emptyTexture = null;
  16601. }
  16602. if (this._emptyCubeTexture) {
  16603. this._releaseTexture(this._emptyCubeTexture);
  16604. this._emptyCubeTexture = null;
  16605. }
  16606. // Rescale PP
  16607. if (this._rescalePostProcess) {
  16608. this._rescalePostProcess.dispose();
  16609. }
  16610. // Release scenes
  16611. while (this.scenes.length) {
  16612. this.scenes[0].dispose();
  16613. }
  16614. // Release audio engine
  16615. if (Engine.audioEngine) {
  16616. Engine.audioEngine.dispose();
  16617. }
  16618. // Release effects
  16619. this.releaseEffects();
  16620. // Unbind
  16621. this.unbindAllAttributes();
  16622. this._boundUniforms = [];
  16623. if (this._dummyFramebuffer) {
  16624. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16625. }
  16626. //WebVR
  16627. this.disableVR();
  16628. // Events
  16629. if (BABYLON.Tools.IsWindowObjectExist()) {
  16630. window.removeEventListener("blur", this._onBlur);
  16631. window.removeEventListener("focus", this._onFocus);
  16632. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16633. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16634. if (this._renderingCanvas) {
  16635. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16636. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16637. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16638. if (!this._doNotHandleContextLost) {
  16639. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16640. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16641. }
  16642. }
  16643. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16644. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16645. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16646. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16647. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16648. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16649. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16650. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16651. if (this._onVrDisplayConnect) {
  16652. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16653. if (this._onVrDisplayDisconnect) {
  16654. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16655. }
  16656. if (this._onVrDisplayPresentChange) {
  16657. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16658. }
  16659. this._onVrDisplayConnect = null;
  16660. this._onVrDisplayDisconnect = null;
  16661. }
  16662. }
  16663. // Remove from Instances
  16664. var index = Engine.Instances.indexOf(this);
  16665. if (index >= 0) {
  16666. Engine.Instances.splice(index, 1);
  16667. }
  16668. this._workingCanvas = null;
  16669. this._workingContext = null;
  16670. this._currentBufferPointers = [];
  16671. this._renderingCanvas = null;
  16672. this._currentProgram = null;
  16673. this._bindedRenderFunction = null;
  16674. this.onResizeObservable.clear();
  16675. this.onCanvasBlurObservable.clear();
  16676. this.onCanvasFocusObservable.clear();
  16677. this.onCanvasPointerOutObservable.clear();
  16678. this.onBeginFrameObservable.clear();
  16679. this.onEndFrameObservable.clear();
  16680. BABYLON.Effect.ResetCache();
  16681. // Abort active requests
  16682. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16683. var request = _a[_i];
  16684. request.abort();
  16685. }
  16686. };
  16687. // Loading screen
  16688. /**
  16689. * Display the loading screen
  16690. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16691. */
  16692. Engine.prototype.displayLoadingUI = function () {
  16693. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16694. return;
  16695. }
  16696. var loadingScreen = this.loadingScreen;
  16697. if (loadingScreen) {
  16698. loadingScreen.displayLoadingUI();
  16699. }
  16700. };
  16701. /**
  16702. * Hide the loading screen
  16703. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16704. */
  16705. Engine.prototype.hideLoadingUI = function () {
  16706. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16707. return;
  16708. }
  16709. var loadingScreen = this.loadingScreen;
  16710. if (loadingScreen) {
  16711. loadingScreen.hideLoadingUI();
  16712. }
  16713. };
  16714. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16715. /**
  16716. * Gets the current loading screen object
  16717. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16718. */
  16719. get: function () {
  16720. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16721. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16722. return this._loadingScreen;
  16723. },
  16724. /**
  16725. * Sets the current loading screen object
  16726. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16727. */
  16728. set: function (loadingScreen) {
  16729. this._loadingScreen = loadingScreen;
  16730. },
  16731. enumerable: true,
  16732. configurable: true
  16733. });
  16734. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16735. /**
  16736. * Sets the current loading screen text
  16737. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16738. */
  16739. set: function (text) {
  16740. this.loadingScreen.loadingUIText = text;
  16741. },
  16742. enumerable: true,
  16743. configurable: true
  16744. });
  16745. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16746. /**
  16747. * Sets the current loading screen background color
  16748. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16749. */
  16750. set: function (color) {
  16751. this.loadingScreen.loadingUIBackgroundColor = color;
  16752. },
  16753. enumerable: true,
  16754. configurable: true
  16755. });
  16756. /**
  16757. * Attach a new callback raised when context lost event is fired
  16758. * @param callback defines the callback to call
  16759. */
  16760. Engine.prototype.attachContextLostEvent = function (callback) {
  16761. if (this._renderingCanvas) {
  16762. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16763. }
  16764. };
  16765. /**
  16766. * Attach a new callback raised when context restored event is fired
  16767. * @param callback defines the callback to call
  16768. */
  16769. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16770. if (this._renderingCanvas) {
  16771. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16772. }
  16773. };
  16774. /**
  16775. * Gets the source code of the vertex shader associated with a specific webGL program
  16776. * @param program defines the program to use
  16777. * @returns a string containing the source code of the vertex shader associated with the program
  16778. */
  16779. Engine.prototype.getVertexShaderSource = function (program) {
  16780. var shaders = this._gl.getAttachedShaders(program);
  16781. if (!shaders) {
  16782. return null;
  16783. }
  16784. return this._gl.getShaderSource(shaders[0]);
  16785. };
  16786. /**
  16787. * Gets the source code of the fragment shader associated with a specific webGL program
  16788. * @param program defines the program to use
  16789. * @returns a string containing the source code of the fragment shader associated with the program
  16790. */
  16791. Engine.prototype.getFragmentShaderSource = function (program) {
  16792. var shaders = this._gl.getAttachedShaders(program);
  16793. if (!shaders) {
  16794. return null;
  16795. }
  16796. return this._gl.getShaderSource(shaders[1]);
  16797. };
  16798. /**
  16799. * Get the current error code of the webGL context
  16800. * @returns the error code
  16801. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16802. */
  16803. Engine.prototype.getError = function () {
  16804. return this._gl.getError();
  16805. };
  16806. // FPS
  16807. /**
  16808. * Gets the current framerate
  16809. * @returns a number representing the framerate
  16810. */
  16811. Engine.prototype.getFps = function () {
  16812. return this._fps;
  16813. };
  16814. /**
  16815. * Gets the time spent between current and previous frame
  16816. * @returns a number representing the delta time in ms
  16817. */
  16818. Engine.prototype.getDeltaTime = function () {
  16819. return this._deltaTime;
  16820. };
  16821. Engine.prototype._measureFps = function () {
  16822. this._performanceMonitor.sampleFrame();
  16823. this._fps = this._performanceMonitor.averageFPS;
  16824. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16825. };
  16826. /** @hidden */
  16827. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16828. if (faceIndex === void 0) { faceIndex = -1; }
  16829. var gl = this._gl;
  16830. if (!this._dummyFramebuffer) {
  16831. var dummy = gl.createFramebuffer();
  16832. if (!dummy) {
  16833. throw new Error("Unable to create dummy framebuffer");
  16834. }
  16835. this._dummyFramebuffer = dummy;
  16836. }
  16837. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16838. if (faceIndex > -1) {
  16839. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16840. }
  16841. else {
  16842. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16843. }
  16844. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16845. var buffer;
  16846. switch (readType) {
  16847. case gl.UNSIGNED_BYTE:
  16848. buffer = new Uint8Array(4 * width * height);
  16849. readType = gl.UNSIGNED_BYTE;
  16850. break;
  16851. default:
  16852. buffer = new Float32Array(4 * width * height);
  16853. readType = gl.FLOAT;
  16854. break;
  16855. }
  16856. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16857. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16858. return buffer;
  16859. };
  16860. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16861. if (this._webGLVersion > 1) {
  16862. return this._caps.colorBufferFloat;
  16863. }
  16864. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16865. };
  16866. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16867. if (this._webGLVersion > 1) {
  16868. return this._caps.colorBufferFloat;
  16869. }
  16870. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16871. };
  16872. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16873. Engine.prototype._canRenderToFramebuffer = function (type) {
  16874. var gl = this._gl;
  16875. //clear existing errors
  16876. while (gl.getError() !== gl.NO_ERROR) { }
  16877. var successful = true;
  16878. var texture = gl.createTexture();
  16879. gl.bindTexture(gl.TEXTURE_2D, texture);
  16880. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16881. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16882. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16883. var fb = gl.createFramebuffer();
  16884. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16885. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16886. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16887. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16888. successful = successful && (gl.getError() === gl.NO_ERROR);
  16889. //try render by clearing frame buffer's color buffer
  16890. if (successful) {
  16891. gl.clear(gl.COLOR_BUFFER_BIT);
  16892. successful = successful && (gl.getError() === gl.NO_ERROR);
  16893. }
  16894. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16895. if (successful) {
  16896. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16897. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16898. var readFormat = gl.RGBA;
  16899. var readType = gl.UNSIGNED_BYTE;
  16900. var buffer = new Uint8Array(4);
  16901. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16902. successful = successful && (gl.getError() === gl.NO_ERROR);
  16903. }
  16904. //clean up
  16905. gl.deleteTexture(texture);
  16906. gl.deleteFramebuffer(fb);
  16907. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16908. //clear accumulated errors
  16909. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16910. return successful;
  16911. };
  16912. /** @hidden */
  16913. Engine.prototype._getWebGLTextureType = function (type) {
  16914. if (type === Engine.TEXTURETYPE_FLOAT) {
  16915. return this._gl.FLOAT;
  16916. }
  16917. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16918. // Add Half Float Constant.
  16919. return this._gl.HALF_FLOAT_OES;
  16920. }
  16921. return this._gl.UNSIGNED_BYTE;
  16922. };
  16923. ;
  16924. Engine.prototype._getInternalFormat = function (format) {
  16925. var internalFormat = this._gl.RGBA;
  16926. switch (format) {
  16927. case Engine.TEXTUREFORMAT_ALPHA:
  16928. internalFormat = this._gl.ALPHA;
  16929. break;
  16930. case Engine.TEXTUREFORMAT_LUMINANCE:
  16931. internalFormat = this._gl.LUMINANCE;
  16932. break;
  16933. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16934. internalFormat = this._gl.LUMINANCE_ALPHA;
  16935. break;
  16936. case Engine.TEXTUREFORMAT_RGB:
  16937. case Engine.TEXTUREFORMAT_RGB32F:
  16938. internalFormat = this._gl.RGB;
  16939. break;
  16940. case Engine.TEXTUREFORMAT_RGBA:
  16941. case Engine.TEXTUREFORMAT_RGBA32F:
  16942. internalFormat = this._gl.RGBA;
  16943. break;
  16944. case Engine.TEXTUREFORMAT_R32F:
  16945. internalFormat = this._gl.RED;
  16946. break;
  16947. case Engine.TEXTUREFORMAT_RG32F:
  16948. internalFormat = this._gl.RG;
  16949. break;
  16950. }
  16951. return internalFormat;
  16952. };
  16953. /** @hidden */
  16954. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16955. if (this._webGLVersion === 1) {
  16956. if (format) {
  16957. switch (format) {
  16958. case Engine.TEXTUREFORMAT_LUMINANCE:
  16959. return this._gl.LUMINANCE;
  16960. }
  16961. }
  16962. return this._gl.RGBA;
  16963. }
  16964. if (type === Engine.TEXTURETYPE_FLOAT) {
  16965. if (format) {
  16966. switch (format) {
  16967. case Engine.TEXTUREFORMAT_R32F:
  16968. return this._gl.R32F;
  16969. case Engine.TEXTUREFORMAT_RG32F:
  16970. return this._gl.RG32F;
  16971. case Engine.TEXTUREFORMAT_RGB32F:
  16972. return this._gl.RGB32F;
  16973. }
  16974. }
  16975. return this._gl.RGBA32F;
  16976. }
  16977. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16978. return this._gl.RGBA16F;
  16979. }
  16980. if (format) {
  16981. switch (format) {
  16982. case Engine.TEXTUREFORMAT_LUMINANCE:
  16983. return this._gl.LUMINANCE;
  16984. case Engine.TEXTUREFORMAT_RGB:
  16985. return this._gl.RGB;
  16986. }
  16987. }
  16988. return this._gl.RGBA;
  16989. };
  16990. ;
  16991. /** @hidden */
  16992. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16993. if (type === Engine.TEXTURETYPE_FLOAT) {
  16994. return this._gl.RGBA32F;
  16995. }
  16996. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16997. return this._gl.RGBA16F;
  16998. }
  16999. return this._gl.RGBA8;
  17000. };
  17001. ;
  17002. /**
  17003. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17004. * @return the new query
  17005. */
  17006. Engine.prototype.createQuery = function () {
  17007. return this._gl.createQuery();
  17008. };
  17009. /**
  17010. * Delete and release a webGL query
  17011. * @param query defines the query to delete
  17012. * @return the current engine
  17013. */
  17014. Engine.prototype.deleteQuery = function (query) {
  17015. this._gl.deleteQuery(query);
  17016. return this;
  17017. };
  17018. /**
  17019. * Check if a given query has resolved and got its value
  17020. * @param query defines the query to check
  17021. * @returns true if the query got its value
  17022. */
  17023. Engine.prototype.isQueryResultAvailable = function (query) {
  17024. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17025. };
  17026. /**
  17027. * Gets the value of a given query
  17028. * @param query defines the query to check
  17029. * @returns the value of the query
  17030. */
  17031. Engine.prototype.getQueryResult = function (query) {
  17032. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17033. };
  17034. /**
  17035. * Initiates an occlusion query
  17036. * @param algorithmType defines the algorithm to use
  17037. * @param query defines the query to use
  17038. * @returns the current engine
  17039. * @see http://doc.babylonjs.com/features/occlusionquery
  17040. */
  17041. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17042. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17043. this._gl.beginQuery(glAlgorithm, query);
  17044. return this;
  17045. };
  17046. /**
  17047. * Ends an occlusion query
  17048. * @see http://doc.babylonjs.com/features/occlusionquery
  17049. * @param algorithmType defines the algorithm to use
  17050. * @returns the current engine
  17051. */
  17052. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17053. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17054. this._gl.endQuery(glAlgorithm);
  17055. return this;
  17056. };
  17057. /* Time queries */
  17058. Engine.prototype._createTimeQuery = function () {
  17059. var timerQuery = this._caps.timerQuery;
  17060. if (timerQuery.createQueryEXT) {
  17061. return timerQuery.createQueryEXT();
  17062. }
  17063. return this.createQuery();
  17064. };
  17065. Engine.prototype._deleteTimeQuery = function (query) {
  17066. var timerQuery = this._caps.timerQuery;
  17067. if (timerQuery.deleteQueryEXT) {
  17068. timerQuery.deleteQueryEXT(query);
  17069. return;
  17070. }
  17071. this.deleteQuery(query);
  17072. };
  17073. Engine.prototype._getTimeQueryResult = function (query) {
  17074. var timerQuery = this._caps.timerQuery;
  17075. if (timerQuery.getQueryObjectEXT) {
  17076. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17077. }
  17078. return this.getQueryResult(query);
  17079. };
  17080. Engine.prototype._getTimeQueryAvailability = function (query) {
  17081. var timerQuery = this._caps.timerQuery;
  17082. if (timerQuery.getQueryObjectEXT) {
  17083. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17084. }
  17085. return this.isQueryResultAvailable(query);
  17086. };
  17087. /**
  17088. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17089. * Please note that only one query can be issued at a time
  17090. * @returns a time token used to track the time span
  17091. */
  17092. Engine.prototype.startTimeQuery = function () {
  17093. var timerQuery = this._caps.timerQuery;
  17094. if (!timerQuery) {
  17095. return null;
  17096. }
  17097. var token = new BABYLON._TimeToken();
  17098. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17099. if (this._caps.canUseTimestampForTimerQuery) {
  17100. token._startTimeQuery = this._createTimeQuery();
  17101. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17102. }
  17103. else {
  17104. if (this._currentNonTimestampToken) {
  17105. return this._currentNonTimestampToken;
  17106. }
  17107. token._timeElapsedQuery = this._createTimeQuery();
  17108. if (timerQuery.beginQueryEXT) {
  17109. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17110. }
  17111. else {
  17112. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17113. }
  17114. this._currentNonTimestampToken = token;
  17115. }
  17116. return token;
  17117. };
  17118. /**
  17119. * Ends a time query
  17120. * @param token defines the token used to measure the time span
  17121. * @returns the time spent (in ns)
  17122. */
  17123. Engine.prototype.endTimeQuery = function (token) {
  17124. var timerQuery = this._caps.timerQuery;
  17125. if (!timerQuery || !token) {
  17126. return -1;
  17127. }
  17128. if (this._caps.canUseTimestampForTimerQuery) {
  17129. if (!token._startTimeQuery) {
  17130. return -1;
  17131. }
  17132. if (!token._endTimeQuery) {
  17133. token._endTimeQuery = this._createTimeQuery();
  17134. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17135. }
  17136. }
  17137. else if (!token._timeElapsedQueryEnded) {
  17138. if (!token._timeElapsedQuery) {
  17139. return -1;
  17140. }
  17141. if (timerQuery.endQueryEXT) {
  17142. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17143. }
  17144. else {
  17145. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17146. }
  17147. token._timeElapsedQueryEnded = true;
  17148. }
  17149. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17150. var available = false;
  17151. if (token._endTimeQuery) {
  17152. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17153. }
  17154. else if (token._timeElapsedQuery) {
  17155. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17156. }
  17157. if (available && !disjoint) {
  17158. var result = 0;
  17159. if (this._caps.canUseTimestampForTimerQuery) {
  17160. if (!token._startTimeQuery || !token._endTimeQuery) {
  17161. return -1;
  17162. }
  17163. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17164. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17165. result = timeEnd - timeStart;
  17166. this._deleteTimeQuery(token._startTimeQuery);
  17167. this._deleteTimeQuery(token._endTimeQuery);
  17168. token._startTimeQuery = null;
  17169. token._endTimeQuery = null;
  17170. }
  17171. else {
  17172. if (!token._timeElapsedQuery) {
  17173. return -1;
  17174. }
  17175. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17176. this._deleteTimeQuery(token._timeElapsedQuery);
  17177. token._timeElapsedQuery = null;
  17178. token._timeElapsedQueryEnded = false;
  17179. this._currentNonTimestampToken = null;
  17180. }
  17181. return result;
  17182. }
  17183. return -1;
  17184. };
  17185. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17186. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17187. };
  17188. // Transform feedback
  17189. /**
  17190. * Creates a webGL transform feedback object
  17191. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17192. * @returns the webGL transform feedback object
  17193. */
  17194. Engine.prototype.createTransformFeedback = function () {
  17195. return this._gl.createTransformFeedback();
  17196. };
  17197. /**
  17198. * Delete a webGL transform feedback object
  17199. * @param value defines the webGL transform feedback object to delete
  17200. */
  17201. Engine.prototype.deleteTransformFeedback = function (value) {
  17202. this._gl.deleteTransformFeedback(value);
  17203. };
  17204. /**
  17205. * Bind a webGL transform feedback object to the webgl context
  17206. * @param value defines the webGL transform feedback object to bind
  17207. */
  17208. Engine.prototype.bindTransformFeedback = function (value) {
  17209. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17210. };
  17211. /**
  17212. * Begins a transform feedback operation
  17213. * @param usePoints defines if points or triangles must be used
  17214. */
  17215. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17216. if (usePoints === void 0) { usePoints = true; }
  17217. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17218. };
  17219. /**
  17220. * Ends a transform feedback operation
  17221. */
  17222. Engine.prototype.endTransformFeedback = function () {
  17223. this._gl.endTransformFeedback();
  17224. };
  17225. /**
  17226. * Specify the varyings to use with transform feedback
  17227. * @param program defines the associated webGL program
  17228. * @param value defines the list of strings representing the varying names
  17229. */
  17230. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17231. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17232. };
  17233. /**
  17234. * Bind a webGL buffer for a transform feedback operation
  17235. * @param value defines the webGL buffer to bind
  17236. */
  17237. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17238. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17239. };
  17240. /** @hidden */
  17241. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17242. var _this = this;
  17243. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17244. this._activeRequests.push(request);
  17245. request.onCompleteObservable.add(function (request) {
  17246. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17247. });
  17248. return request;
  17249. };
  17250. /** @hidden */
  17251. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17252. var _this = this;
  17253. return new Promise(function (resolve, reject) {
  17254. _this._loadFile(url, function (data) {
  17255. resolve(data);
  17256. }, undefined, database, useArrayBuffer, function (request, exception) {
  17257. reject(exception);
  17258. });
  17259. });
  17260. };
  17261. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17262. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17263. var onload = function (data) {
  17264. loadedFiles[index] = data;
  17265. loadedFiles._internalCount++;
  17266. if (loadedFiles._internalCount === 6) {
  17267. onfinish(loadedFiles);
  17268. }
  17269. };
  17270. var onerror = function (request, exception) {
  17271. if (onErrorCallBack && request) {
  17272. onErrorCallBack(request.status + " " + request.statusText, exception);
  17273. }
  17274. };
  17275. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17276. };
  17277. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17278. if (onError === void 0) { onError = null; }
  17279. var loadedFiles = [];
  17280. loadedFiles._internalCount = 0;
  17281. for (var index = 0; index < 6; index++) {
  17282. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17283. }
  17284. };
  17285. // Statics
  17286. /**
  17287. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17288. * @returns true if the engine can be created
  17289. * @ignorenaming
  17290. */
  17291. Engine.isSupported = function () {
  17292. try {
  17293. var tempcanvas = document.createElement("canvas");
  17294. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17295. return gl != null && !!window.WebGLRenderingContext;
  17296. }
  17297. catch (e) {
  17298. return false;
  17299. }
  17300. };
  17301. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17302. Engine.ExceptionList = [
  17303. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17304. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17305. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17306. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17307. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17308. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17309. ];
  17310. /** Gets the list of created engines */
  17311. Engine.Instances = new Array();
  17312. // Const statics
  17313. Engine._ALPHA_DISABLE = 0;
  17314. Engine._ALPHA_ADD = 1;
  17315. Engine._ALPHA_COMBINE = 2;
  17316. Engine._ALPHA_SUBTRACT = 3;
  17317. Engine._ALPHA_MULTIPLY = 4;
  17318. Engine._ALPHA_MAXIMIZED = 5;
  17319. Engine._ALPHA_ONEONE = 6;
  17320. Engine._ALPHA_PREMULTIPLIED = 7;
  17321. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17322. Engine._ALPHA_INTERPOLATE = 9;
  17323. Engine._ALPHA_SCREENMODE = 10;
  17324. Engine._DELAYLOADSTATE_NONE = 0;
  17325. Engine._DELAYLOADSTATE_LOADED = 1;
  17326. Engine._DELAYLOADSTATE_LOADING = 2;
  17327. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17328. Engine._TEXTUREFORMAT_ALPHA = 0;
  17329. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17330. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17331. Engine._TEXTUREFORMAT_RGB = 4;
  17332. Engine._TEXTUREFORMAT_RGBA = 5;
  17333. Engine._TEXTUREFORMAT_R32F = 6;
  17334. Engine._TEXTUREFORMAT_RG32F = 7;
  17335. Engine._TEXTUREFORMAT_RGB32F = 8;
  17336. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17337. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17338. Engine._TEXTURETYPE_FLOAT = 1;
  17339. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17340. // Depht or Stencil test Constants.
  17341. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17342. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  17343. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  17344. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  17345. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  17346. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  17347. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  17348. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  17349. // Stencil Actions Constants.
  17350. Engine._KEEP = 0x1E00;
  17351. Engine._REPLACE = 0x1E01;
  17352. Engine._INCR = 0x1E02;
  17353. Engine._DECR = 0x1E03;
  17354. Engine._INVERT = 0x150A;
  17355. Engine._INCR_WRAP = 0x8507;
  17356. Engine._DECR_WRAP = 0x8508;
  17357. // Texture rescaling mode
  17358. Engine._SCALEMODE_FLOOR = 1;
  17359. Engine._SCALEMODE_NEAREST = 2;
  17360. Engine._SCALEMODE_CEILING = 3;
  17361. // Updatable statics so stick with vars here
  17362. /**
  17363. * Gets or sets the epsilon value used by collision engine
  17364. */
  17365. Engine.CollisionsEpsilon = 0.001;
  17366. /**
  17367. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17368. */
  17369. Engine.CodeRepository = "src/";
  17370. /**
  17371. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17372. */
  17373. Engine.ShadersRepository = "src/Shaders/";
  17374. return Engine;
  17375. }());
  17376. BABYLON.Engine = Engine;
  17377. })(BABYLON || (BABYLON = {}));
  17378. //# sourceMappingURL=babylon.engine.js.map
  17379. var BABYLON;
  17380. (function (BABYLON) {
  17381. /**
  17382. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17383. */
  17384. var Node = /** @class */ (function () {
  17385. /**
  17386. * Creates a new Node
  17387. * @param {string} name - the name and id to be given to this node
  17388. * @param {BABYLON.Scene} the scene this node will be added to
  17389. */
  17390. function Node(name, scene) {
  17391. if (scene === void 0) { scene = null; }
  17392. /**
  17393. * Gets or sets a string used to store user defined state for the node
  17394. */
  17395. this.state = "";
  17396. /**
  17397. * Gets or sets an object used to store user defined information for the node
  17398. */
  17399. this.metadata = null;
  17400. /**
  17401. * Gets or sets a boolean used to define if the node must be serialized
  17402. */
  17403. this.doNotSerialize = false;
  17404. /** @hidden */
  17405. this._isDisposed = false;
  17406. /**
  17407. * Gets a list of Animations associated with the node
  17408. */
  17409. this.animations = new Array();
  17410. this._ranges = {};
  17411. this._isEnabled = true;
  17412. this._isReady = true;
  17413. /** @hidden */
  17414. this._currentRenderId = -1;
  17415. this._parentRenderId = -1;
  17416. this._childRenderId = -1;
  17417. this._animationPropertiesOverride = null;
  17418. /**
  17419. * An event triggered when the mesh is disposed
  17420. */
  17421. this.onDisposeObservable = new BABYLON.Observable();
  17422. // Behaviors
  17423. this._behaviors = new Array();
  17424. this.name = name;
  17425. this.id = name;
  17426. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17427. this.uniqueId = this._scene.getUniqueId();
  17428. this._initCache();
  17429. }
  17430. /**
  17431. * Gets a boolean indicating if the node has been disposed
  17432. * @returns true if the node was disposed
  17433. */
  17434. Node.prototype.isDisposed = function () {
  17435. return this._isDisposed;
  17436. };
  17437. Object.defineProperty(Node.prototype, "parent", {
  17438. get: function () {
  17439. return this._parentNode;
  17440. },
  17441. /**
  17442. * Gets or sets the parent of the node
  17443. */
  17444. set: function (parent) {
  17445. if (this._parentNode === parent) {
  17446. return;
  17447. }
  17448. // Remove self from list of children of parent
  17449. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17450. var index = this._parentNode._children.indexOf(this);
  17451. if (index !== -1) {
  17452. this._parentNode._children.splice(index, 1);
  17453. }
  17454. }
  17455. // Store new parent
  17456. this._parentNode = parent;
  17457. // Add as child to new parent
  17458. if (this._parentNode) {
  17459. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17460. this._parentNode._children = new Array();
  17461. }
  17462. this._parentNode._children.push(this);
  17463. }
  17464. },
  17465. enumerable: true,
  17466. configurable: true
  17467. });
  17468. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17469. /**
  17470. * Gets or sets the animation properties override
  17471. */
  17472. get: function () {
  17473. if (!this._animationPropertiesOverride) {
  17474. return this._scene.animationPropertiesOverride;
  17475. }
  17476. return this._animationPropertiesOverride;
  17477. },
  17478. set: function (value) {
  17479. this._animationPropertiesOverride = value;
  17480. },
  17481. enumerable: true,
  17482. configurable: true
  17483. });
  17484. /**
  17485. * Gets a string idenfifying the name of the class
  17486. * @returns "Node" string
  17487. */
  17488. Node.prototype.getClassName = function () {
  17489. return "Node";
  17490. };
  17491. Object.defineProperty(Node.prototype, "onDispose", {
  17492. /**
  17493. * Sets a callback that will be raised when the node will be disposed
  17494. */
  17495. set: function (callback) {
  17496. if (this._onDisposeObserver) {
  17497. this.onDisposeObservable.remove(this._onDisposeObserver);
  17498. }
  17499. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17500. },
  17501. enumerable: true,
  17502. configurable: true
  17503. });
  17504. /**
  17505. * Gets the scene of the node
  17506. * @returns a {BABYLON.Scene}
  17507. */
  17508. Node.prototype.getScene = function () {
  17509. return this._scene;
  17510. };
  17511. /**
  17512. * Gets the engine of the node
  17513. * @returns a {BABYLON.Engine}
  17514. */
  17515. Node.prototype.getEngine = function () {
  17516. return this._scene.getEngine();
  17517. };
  17518. /**
  17519. * Attach a behavior to the node
  17520. * @see http://doc.babylonjs.com/features/behaviour
  17521. * @param behavior defines the behavior to attach
  17522. * @returns the current Node
  17523. */
  17524. Node.prototype.addBehavior = function (behavior) {
  17525. var _this = this;
  17526. var index = this._behaviors.indexOf(behavior);
  17527. if (index !== -1) {
  17528. return this;
  17529. }
  17530. behavior.init();
  17531. if (this._scene.isLoading) {
  17532. // We defer the attach when the scene will be loaded
  17533. var observer = this._scene.onDataLoadedObservable.add(function () {
  17534. behavior.attach(_this);
  17535. setTimeout(function () {
  17536. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17537. _this._scene.onDataLoadedObservable.remove(observer);
  17538. }, 0);
  17539. });
  17540. }
  17541. else {
  17542. behavior.attach(this);
  17543. }
  17544. this._behaviors.push(behavior);
  17545. return this;
  17546. };
  17547. /**
  17548. * Remove an attached behavior
  17549. * @see http://doc.babylonjs.com/features/behaviour
  17550. * @param behavior defines the behavior to attach
  17551. * @returns the current Node
  17552. */
  17553. Node.prototype.removeBehavior = function (behavior) {
  17554. var index = this._behaviors.indexOf(behavior);
  17555. if (index === -1) {
  17556. return this;
  17557. }
  17558. this._behaviors[index].detach();
  17559. this._behaviors.splice(index, 1);
  17560. return this;
  17561. };
  17562. Object.defineProperty(Node.prototype, "behaviors", {
  17563. /**
  17564. * Gets the list of attached behaviors
  17565. * @see http://doc.babylonjs.com/features/behaviour
  17566. */
  17567. get: function () {
  17568. return this._behaviors;
  17569. },
  17570. enumerable: true,
  17571. configurable: true
  17572. });
  17573. /**
  17574. * Gets an attached behavior by name
  17575. * @param name defines the name of the behavior to look for
  17576. * @see http://doc.babylonjs.com/features/behaviour
  17577. * @returns null if behavior was not found else the requested behavior
  17578. */
  17579. Node.prototype.getBehaviorByName = function (name) {
  17580. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17581. var behavior = _a[_i];
  17582. if (behavior.name === name) {
  17583. return behavior;
  17584. }
  17585. }
  17586. return null;
  17587. };
  17588. /**
  17589. * Returns the world matrix of the node
  17590. * @returns a matrix containing the node's world matrix
  17591. */
  17592. Node.prototype.getWorldMatrix = function () {
  17593. return BABYLON.Matrix.Identity();
  17594. };
  17595. /** @hidden */
  17596. Node.prototype._getWorldMatrixDeterminant = function () {
  17597. return 1;
  17598. };
  17599. // override it in derived class if you add new variables to the cache
  17600. // and call the parent class method
  17601. /** @hidden */
  17602. Node.prototype._initCache = function () {
  17603. this._cache = {};
  17604. this._cache.parent = undefined;
  17605. };
  17606. /** @hidden */
  17607. Node.prototype.updateCache = function (force) {
  17608. if (!force && this.isSynchronized())
  17609. return;
  17610. this._cache.parent = this.parent;
  17611. this._updateCache();
  17612. };
  17613. // override it in derived class if you add new variables to the cache
  17614. // and call the parent class method if !ignoreParentClass
  17615. /** @hidden */
  17616. Node.prototype._updateCache = function (ignoreParentClass) {
  17617. };
  17618. // override it in derived class if you add new variables to the cache
  17619. /** @hidden */
  17620. Node.prototype._isSynchronized = function () {
  17621. return true;
  17622. };
  17623. /** @hidden */
  17624. Node.prototype._markSyncedWithParent = function () {
  17625. if (this.parent) {
  17626. this._parentRenderId = this.parent._childRenderId;
  17627. }
  17628. };
  17629. /** @hidden */
  17630. Node.prototype.isSynchronizedWithParent = function () {
  17631. if (!this.parent) {
  17632. return true;
  17633. }
  17634. if (this._parentRenderId !== this.parent._childRenderId) {
  17635. return false;
  17636. }
  17637. return this.parent.isSynchronized();
  17638. };
  17639. /** @hidden */
  17640. Node.prototype.isSynchronized = function (updateCache) {
  17641. var check = this.hasNewParent();
  17642. check = check || !this.isSynchronizedWithParent();
  17643. check = check || !this._isSynchronized();
  17644. if (updateCache)
  17645. this.updateCache(true);
  17646. return !check;
  17647. };
  17648. /** @hidden */
  17649. Node.prototype.hasNewParent = function (update) {
  17650. if (this._cache.parent === this.parent)
  17651. return false;
  17652. if (update)
  17653. this._cache.parent = this.parent;
  17654. return true;
  17655. };
  17656. /**
  17657. * Is this node ready to be used/rendered
  17658. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17659. * @return true if the node is ready
  17660. */
  17661. Node.prototype.isReady = function (completeCheck) {
  17662. if (completeCheck === void 0) { completeCheck = false; }
  17663. return this._isReady;
  17664. };
  17665. /**
  17666. * Is this node enabled?
  17667. * 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
  17668. * @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
  17669. * @return whether this node (and its parent) is enabled
  17670. */
  17671. Node.prototype.isEnabled = function (checkAncestors) {
  17672. if (checkAncestors === void 0) { checkAncestors = true; }
  17673. if (checkAncestors === false) {
  17674. return this._isEnabled;
  17675. }
  17676. if (this._isEnabled === false) {
  17677. return false;
  17678. }
  17679. if (this.parent !== undefined && this.parent !== null) {
  17680. return this.parent.isEnabled(checkAncestors);
  17681. }
  17682. return true;
  17683. };
  17684. /**
  17685. * Set the enabled state of this node
  17686. * @param value defines the new enabled state
  17687. */
  17688. Node.prototype.setEnabled = function (value) {
  17689. this._isEnabled = value;
  17690. };
  17691. /**
  17692. * Is this node a descendant of the given node?
  17693. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17694. * @param ancestor defines the parent node to inspect
  17695. * @returns a boolean indicating if this node is a descendant of the given node
  17696. */
  17697. Node.prototype.isDescendantOf = function (ancestor) {
  17698. if (this.parent) {
  17699. if (this.parent === ancestor) {
  17700. return true;
  17701. }
  17702. return this.parent.isDescendantOf(ancestor);
  17703. }
  17704. return false;
  17705. };
  17706. /** @hidden */
  17707. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17708. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17709. if (!this._children) {
  17710. return;
  17711. }
  17712. for (var index = 0; index < this._children.length; index++) {
  17713. var item = this._children[index];
  17714. if (!predicate || predicate(item)) {
  17715. results.push(item);
  17716. }
  17717. if (!directDescendantsOnly) {
  17718. item._getDescendants(results, false, predicate);
  17719. }
  17720. }
  17721. };
  17722. /**
  17723. * Will return all nodes that have this node as ascendant
  17724. * @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
  17725. * @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
  17726. * @return all children nodes of all types
  17727. */
  17728. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17729. var results = new Array();
  17730. this._getDescendants(results, directDescendantsOnly, predicate);
  17731. return results;
  17732. };
  17733. /**
  17734. * Get all child-meshes of this node
  17735. * @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
  17736. * @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
  17737. * @returns an array of {BABYLON.AbstractMesh}
  17738. */
  17739. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17740. var results = [];
  17741. this._getDescendants(results, directDescendantsOnly, function (node) {
  17742. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17743. });
  17744. return results;
  17745. };
  17746. /**
  17747. * Get all child-transformNodes of this node
  17748. * @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
  17749. * @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
  17750. * @returns an array of {BABYLON.TransformNode}
  17751. */
  17752. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17753. var results = [];
  17754. this._getDescendants(results, directDescendantsOnly, function (node) {
  17755. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17756. });
  17757. return results;
  17758. };
  17759. /**
  17760. * Get all direct children of this node
  17761. * @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
  17762. * @returns an array of {BABYLON.Node}
  17763. */
  17764. Node.prototype.getChildren = function (predicate) {
  17765. return this.getDescendants(true, predicate);
  17766. };
  17767. /** @hidden */
  17768. Node.prototype._setReady = function (state) {
  17769. if (state === this._isReady) {
  17770. return;
  17771. }
  17772. if (!state) {
  17773. this._isReady = false;
  17774. return;
  17775. }
  17776. if (this.onReady) {
  17777. this.onReady(this);
  17778. }
  17779. this._isReady = true;
  17780. };
  17781. /**
  17782. * Get an animation by name
  17783. * @param name defines the name of the animation to look for
  17784. * @returns null if not found else the requested animation
  17785. */
  17786. Node.prototype.getAnimationByName = function (name) {
  17787. for (var i = 0; i < this.animations.length; i++) {
  17788. var animation = this.animations[i];
  17789. if (animation.name === name) {
  17790. return animation;
  17791. }
  17792. }
  17793. return null;
  17794. };
  17795. /**
  17796. * Creates an animation range for this node
  17797. * @param name defines the name of the range
  17798. * @param from defines the starting key
  17799. * @param to defines the end key
  17800. */
  17801. Node.prototype.createAnimationRange = function (name, from, to) {
  17802. // check name not already in use
  17803. if (!this._ranges[name]) {
  17804. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17805. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17806. if (this.animations[i]) {
  17807. this.animations[i].createRange(name, from, to);
  17808. }
  17809. }
  17810. }
  17811. };
  17812. /**
  17813. * Delete a specific animation range
  17814. * @param name defines the name of the range to delete
  17815. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17816. */
  17817. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17818. if (deleteFrames === void 0) { deleteFrames = true; }
  17819. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17820. if (this.animations[i]) {
  17821. this.animations[i].deleteRange(name, deleteFrames);
  17822. }
  17823. }
  17824. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17825. };
  17826. /**
  17827. * Get an animation range by name
  17828. * @param name defines the name of the animation range to look for
  17829. * @returns null if not found else the requested animation range
  17830. */
  17831. Node.prototype.getAnimationRange = function (name) {
  17832. return this._ranges[name];
  17833. };
  17834. /**
  17835. * Will start the animation sequence
  17836. * @param name defines the range frames for animation sequence
  17837. * @param loop defines if the animation should loop (false by default)
  17838. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17839. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17840. * @returns the object created for this animation. If range does not exist, it will return null
  17841. */
  17842. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17843. var range = this.getAnimationRange(name);
  17844. if (!range) {
  17845. return null;
  17846. }
  17847. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17848. };
  17849. /**
  17850. * Serialize animation ranges into a JSON compatible object
  17851. * @returns serialization object
  17852. */
  17853. Node.prototype.serializeAnimationRanges = function () {
  17854. var serializationRanges = [];
  17855. for (var name in this._ranges) {
  17856. var localRange = this._ranges[name];
  17857. if (!localRange) {
  17858. continue;
  17859. }
  17860. var range = {};
  17861. range.name = name;
  17862. range.from = localRange.from;
  17863. range.to = localRange.to;
  17864. serializationRanges.push(range);
  17865. }
  17866. return serializationRanges;
  17867. };
  17868. /**
  17869. * Computes the world matrix of the node
  17870. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17871. * @returns the world matrix
  17872. */
  17873. Node.prototype.computeWorldMatrix = function (force) {
  17874. return BABYLON.Matrix.Identity();
  17875. };
  17876. /**
  17877. * Releases resources associated with this node.
  17878. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17879. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17880. */
  17881. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17882. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17883. if (!doNotRecurse) {
  17884. var nodes = this.getDescendants(true);
  17885. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17886. var node = nodes_1[_i];
  17887. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17888. }
  17889. }
  17890. else {
  17891. var transformNodes = this.getChildTransformNodes(true);
  17892. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17893. var transformNode = transformNodes_1[_a];
  17894. transformNode.parent = null;
  17895. transformNode.computeWorldMatrix(true);
  17896. }
  17897. }
  17898. this.parent = null;
  17899. // Callback
  17900. this.onDisposeObservable.notifyObservers(this);
  17901. this.onDisposeObservable.clear();
  17902. // Behaviors
  17903. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17904. var behavior = _c[_b];
  17905. behavior.detach();
  17906. }
  17907. this._behaviors = [];
  17908. this._isDisposed = true;
  17909. };
  17910. /**
  17911. * Parse animation range data from a serialization object and store them into a given node
  17912. * @param node defines where to store the animation ranges
  17913. * @param parsedNode defines the serialization object to read data from
  17914. * @param scene defines the hosting scene
  17915. */
  17916. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17917. if (parsedNode.ranges) {
  17918. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17919. var data = parsedNode.ranges[index];
  17920. node.createAnimationRange(data.name, data.from, data.to);
  17921. }
  17922. }
  17923. };
  17924. __decorate([
  17925. BABYLON.serialize()
  17926. ], Node.prototype, "name", void 0);
  17927. __decorate([
  17928. BABYLON.serialize()
  17929. ], Node.prototype, "id", void 0);
  17930. __decorate([
  17931. BABYLON.serialize()
  17932. ], Node.prototype, "uniqueId", void 0);
  17933. __decorate([
  17934. BABYLON.serialize()
  17935. ], Node.prototype, "state", void 0);
  17936. __decorate([
  17937. BABYLON.serialize()
  17938. ], Node.prototype, "metadata", void 0);
  17939. return Node;
  17940. }());
  17941. BABYLON.Node = Node;
  17942. })(BABYLON || (BABYLON = {}));
  17943. //# sourceMappingURL=babylon.node.js.map
  17944. var BABYLON;
  17945. (function (BABYLON) {
  17946. var BoundingSphere = /** @class */ (function () {
  17947. /**
  17948. * Creates a new bounding sphere
  17949. * @param min defines the minimum vector (in local space)
  17950. * @param max defines the maximum vector (in local space)
  17951. */
  17952. function BoundingSphere(min, max) {
  17953. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17954. this.reConstruct(min, max);
  17955. }
  17956. /**
  17957. * Recreates the entire bounding sphere from scratch
  17958. * @param min defines the new minimum vector (in local space)
  17959. * @param max defines the new maximum vector (in local space)
  17960. */
  17961. BoundingSphere.prototype.reConstruct = function (min, max) {
  17962. this.minimum = min.clone();
  17963. this.maximum = max.clone();
  17964. var distance = BABYLON.Vector3.Distance(min, max);
  17965. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17966. this.radius = distance * 0.5;
  17967. this.centerWorld = BABYLON.Vector3.Zero();
  17968. this._update(BABYLON.Matrix.Identity());
  17969. };
  17970. // Methods
  17971. BoundingSphere.prototype._update = function (world) {
  17972. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17973. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17974. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17975. };
  17976. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17977. for (var i = 0; i < 6; i++) {
  17978. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17979. return false;
  17980. }
  17981. return true;
  17982. };
  17983. BoundingSphere.prototype.intersectsPoint = function (point) {
  17984. var x = this.centerWorld.x - point.x;
  17985. var y = this.centerWorld.y - point.y;
  17986. var z = this.centerWorld.z - point.z;
  17987. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17988. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17989. return false;
  17990. return true;
  17991. };
  17992. // Statics
  17993. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17994. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17995. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17996. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17997. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17998. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17999. return false;
  18000. return true;
  18001. };
  18002. return BoundingSphere;
  18003. }());
  18004. BABYLON.BoundingSphere = BoundingSphere;
  18005. })(BABYLON || (BABYLON = {}));
  18006. //# sourceMappingURL=babylon.boundingSphere.js.map
  18007. var BABYLON;
  18008. (function (BABYLON) {
  18009. var BoundingBox = /** @class */ (function () {
  18010. /**
  18011. * Creates a new bounding box
  18012. * @param min defines the minimum vector (in local space)
  18013. * @param max defines the maximum vector (in local space)
  18014. */
  18015. function BoundingBox(min, max) {
  18016. this.vectorsWorld = new Array();
  18017. this.reConstruct(min, max);
  18018. }
  18019. // Methods
  18020. /**
  18021. * Recreates the entire bounding box from scratch
  18022. * @param min defines the new minimum vector (in local space)
  18023. * @param max defines the new maximum vector (in local space)
  18024. */
  18025. BoundingBox.prototype.reConstruct = function (min, max) {
  18026. this.minimum = min.clone();
  18027. this.maximum = max.clone();
  18028. // Bounding vectors
  18029. this.vectors = new Array();
  18030. this.vectors.push(this.minimum.clone());
  18031. this.vectors.push(this.maximum.clone());
  18032. this.vectors.push(this.minimum.clone());
  18033. this.vectors[2].x = this.maximum.x;
  18034. this.vectors.push(this.minimum.clone());
  18035. this.vectors[3].y = this.maximum.y;
  18036. this.vectors.push(this.minimum.clone());
  18037. this.vectors[4].z = this.maximum.z;
  18038. this.vectors.push(this.maximum.clone());
  18039. this.vectors[5].z = this.minimum.z;
  18040. this.vectors.push(this.maximum.clone());
  18041. this.vectors[6].x = this.minimum.x;
  18042. this.vectors.push(this.maximum.clone());
  18043. this.vectors[7].y = this.minimum.y;
  18044. // OBB
  18045. this.center = this.maximum.add(this.minimum).scale(0.5);
  18046. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18047. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18048. // World
  18049. for (var index = 0; index < this.vectors.length; index++) {
  18050. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18051. }
  18052. this.minimumWorld = BABYLON.Vector3.Zero();
  18053. this.maximumWorld = BABYLON.Vector3.Zero();
  18054. this.centerWorld = BABYLON.Vector3.Zero();
  18055. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18056. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18057. };
  18058. BoundingBox.prototype.getWorldMatrix = function () {
  18059. return this._worldMatrix;
  18060. };
  18061. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18062. this._worldMatrix.copyFrom(matrix);
  18063. return this;
  18064. };
  18065. BoundingBox.prototype._update = function (world) {
  18066. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18067. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18068. for (var index = 0; index < this.vectors.length; index++) {
  18069. var v = this.vectorsWorld[index];
  18070. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18071. if (v.x < this.minimumWorld.x)
  18072. this.minimumWorld.x = v.x;
  18073. if (v.y < this.minimumWorld.y)
  18074. this.minimumWorld.y = v.y;
  18075. if (v.z < this.minimumWorld.z)
  18076. this.minimumWorld.z = v.z;
  18077. if (v.x > this.maximumWorld.x)
  18078. this.maximumWorld.x = v.x;
  18079. if (v.y > this.maximumWorld.y)
  18080. this.maximumWorld.y = v.y;
  18081. if (v.z > this.maximumWorld.z)
  18082. this.maximumWorld.z = v.z;
  18083. }
  18084. // Extend
  18085. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18086. this.extendSizeWorld.scaleInPlace(0.5);
  18087. // OBB
  18088. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18089. this.centerWorld.scaleInPlace(0.5);
  18090. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18091. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18092. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18093. this._worldMatrix = world;
  18094. };
  18095. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18096. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18097. };
  18098. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18099. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18100. };
  18101. BoundingBox.prototype.intersectsPoint = function (point) {
  18102. var delta = -BABYLON.Epsilon;
  18103. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18104. return false;
  18105. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18106. return false;
  18107. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18108. return false;
  18109. return true;
  18110. };
  18111. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18112. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18113. };
  18114. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18115. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18116. return false;
  18117. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18118. return false;
  18119. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18120. return false;
  18121. return true;
  18122. };
  18123. // Statics
  18124. BoundingBox.Intersects = function (box0, box1) {
  18125. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18126. return false;
  18127. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18128. return false;
  18129. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18130. return false;
  18131. return true;
  18132. };
  18133. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18134. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18135. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18136. return (num <= (sphereRadius * sphereRadius));
  18137. };
  18138. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18139. for (var p = 0; p < 6; p++) {
  18140. for (var i = 0; i < 8; i++) {
  18141. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18142. return false;
  18143. }
  18144. }
  18145. }
  18146. return true;
  18147. };
  18148. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18149. for (var p = 0; p < 6; p++) {
  18150. var inCount = 8;
  18151. for (var i = 0; i < 8; i++) {
  18152. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18153. --inCount;
  18154. }
  18155. else {
  18156. break;
  18157. }
  18158. }
  18159. if (inCount === 0)
  18160. return false;
  18161. }
  18162. return true;
  18163. };
  18164. return BoundingBox;
  18165. }());
  18166. BABYLON.BoundingBox = BoundingBox;
  18167. })(BABYLON || (BABYLON = {}));
  18168. //# sourceMappingURL=babylon.boundingBox.js.map
  18169. var BABYLON;
  18170. (function (BABYLON) {
  18171. var computeBoxExtents = function (axis, box) {
  18172. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18173. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18174. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18175. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18176. var r = r0 + r1 + r2;
  18177. return {
  18178. min: p - r,
  18179. max: p + r
  18180. };
  18181. };
  18182. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18183. var axisOverlap = function (axis, box0, box1) {
  18184. var result0 = computeBoxExtents(axis, box0);
  18185. var result1 = computeBoxExtents(axis, box1);
  18186. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18187. };
  18188. var BoundingInfo = /** @class */ (function () {
  18189. function BoundingInfo(minimum, maximum) {
  18190. this.minimum = minimum;
  18191. this.maximum = maximum;
  18192. this._isLocked = false;
  18193. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18194. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18195. }
  18196. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18197. get: function () {
  18198. return this._isLocked;
  18199. },
  18200. set: function (value) {
  18201. this._isLocked = value;
  18202. },
  18203. enumerable: true,
  18204. configurable: true
  18205. });
  18206. // Methods
  18207. BoundingInfo.prototype.update = function (world) {
  18208. if (this._isLocked) {
  18209. return;
  18210. }
  18211. this.boundingBox._update(world);
  18212. this.boundingSphere._update(world);
  18213. };
  18214. /**
  18215. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18216. * @param center New center of the bounding info
  18217. * @param extend New extend of the bounding info
  18218. */
  18219. BoundingInfo.prototype.centerOn = function (center, extend) {
  18220. this.minimum = center.subtract(extend);
  18221. this.maximum = center.add(extend);
  18222. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18223. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18224. return this;
  18225. };
  18226. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18227. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18228. return false;
  18229. return this.boundingBox.isInFrustum(frustumPlanes);
  18230. };
  18231. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18232. /**
  18233. * Gets the world distance between the min and max points of the bounding box
  18234. */
  18235. get: function () {
  18236. var boundingBox = this.boundingBox;
  18237. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18238. return size.length();
  18239. },
  18240. enumerable: true,
  18241. configurable: true
  18242. });
  18243. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18244. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18245. };
  18246. BoundingInfo.prototype._checkCollision = function (collider) {
  18247. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18248. };
  18249. BoundingInfo.prototype.intersectsPoint = function (point) {
  18250. if (!this.boundingSphere.centerWorld) {
  18251. return false;
  18252. }
  18253. if (!this.boundingSphere.intersectsPoint(point)) {
  18254. return false;
  18255. }
  18256. if (!this.boundingBox.intersectsPoint(point)) {
  18257. return false;
  18258. }
  18259. return true;
  18260. };
  18261. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18262. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18263. return false;
  18264. }
  18265. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18266. return false;
  18267. }
  18268. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18269. return false;
  18270. }
  18271. if (!precise) {
  18272. return true;
  18273. }
  18274. var box0 = this.boundingBox;
  18275. var box1 = boundingInfo.boundingBox;
  18276. if (!axisOverlap(box0.directions[0], box0, box1))
  18277. return false;
  18278. if (!axisOverlap(box0.directions[1], box0, box1))
  18279. return false;
  18280. if (!axisOverlap(box0.directions[2], box0, box1))
  18281. return false;
  18282. if (!axisOverlap(box1.directions[0], box0, box1))
  18283. return false;
  18284. if (!axisOverlap(box1.directions[1], box0, box1))
  18285. return false;
  18286. if (!axisOverlap(box1.directions[2], box0, box1))
  18287. return false;
  18288. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18289. return false;
  18290. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18291. return false;
  18292. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18293. return false;
  18294. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18295. return false;
  18296. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18297. return false;
  18298. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18299. return false;
  18300. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18301. return false;
  18302. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18303. return false;
  18304. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18305. return false;
  18306. return true;
  18307. };
  18308. return BoundingInfo;
  18309. }());
  18310. BABYLON.BoundingInfo = BoundingInfo;
  18311. })(BABYLON || (BABYLON = {}));
  18312. //# sourceMappingURL=babylon.boundingInfo.js.map
  18313. var BABYLON;
  18314. (function (BABYLON) {
  18315. var TransformNode = /** @class */ (function (_super) {
  18316. __extends(TransformNode, _super);
  18317. function TransformNode(name, scene, isPure) {
  18318. if (scene === void 0) { scene = null; }
  18319. if (isPure === void 0) { isPure = true; }
  18320. var _this = _super.call(this, name, scene) || this;
  18321. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18322. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18323. _this._up = new BABYLON.Vector3(0, 1, 0);
  18324. _this._right = new BABYLON.Vector3(1, 0, 0);
  18325. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18326. // Properties
  18327. _this._rotation = BABYLON.Vector3.Zero();
  18328. _this._scaling = BABYLON.Vector3.One();
  18329. _this._isDirty = false;
  18330. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18331. _this.scalingDeterminant = 1;
  18332. _this.infiniteDistance = false;
  18333. _this.position = BABYLON.Vector3.Zero();
  18334. _this._localWorld = BABYLON.Matrix.Zero();
  18335. _this._worldMatrix = BABYLON.Matrix.Zero();
  18336. _this._worldMatrixDeterminant = 0;
  18337. _this._absolutePosition = BABYLON.Vector3.Zero();
  18338. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18339. _this._postMultiplyPivotMatrix = false;
  18340. _this._isWorldMatrixFrozen = false;
  18341. /**
  18342. * An event triggered after the world matrix is updated
  18343. */
  18344. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18345. _this._nonUniformScaling = false;
  18346. if (isPure) {
  18347. _this.getScene().addTransformNode(_this);
  18348. }
  18349. return _this;
  18350. }
  18351. /**
  18352. * Gets a string idenfifying the name of the class
  18353. * @returns "TransformNode" string
  18354. */
  18355. TransformNode.prototype.getClassName = function () {
  18356. return "TransformNode";
  18357. };
  18358. Object.defineProperty(TransformNode.prototype, "rotation", {
  18359. /**
  18360. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18361. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18362. * Default : (0.0, 0.0, 0.0)
  18363. */
  18364. get: function () {
  18365. return this._rotation;
  18366. },
  18367. set: function (newRotation) {
  18368. this._rotation = newRotation;
  18369. },
  18370. enumerable: true,
  18371. configurable: true
  18372. });
  18373. Object.defineProperty(TransformNode.prototype, "scaling", {
  18374. /**
  18375. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18376. * Default : (1.0, 1.0, 1.0)
  18377. */
  18378. get: function () {
  18379. return this._scaling;
  18380. },
  18381. /**
  18382. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18383. * Default : (1.0, 1.0, 1.0)
  18384. */
  18385. set: function (newScaling) {
  18386. this._scaling = newScaling;
  18387. },
  18388. enumerable: true,
  18389. configurable: true
  18390. });
  18391. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18392. /**
  18393. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18394. * It's null by default.
  18395. * 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)
  18396. */
  18397. get: function () {
  18398. return this._rotationQuaternion;
  18399. },
  18400. set: function (quaternion) {
  18401. this._rotationQuaternion = quaternion;
  18402. //reset the rotation vector.
  18403. if (quaternion && this.rotation.length()) {
  18404. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18405. }
  18406. },
  18407. enumerable: true,
  18408. configurable: true
  18409. });
  18410. Object.defineProperty(TransformNode.prototype, "forward", {
  18411. /**
  18412. * The forward direction of that transform in world space.
  18413. */
  18414. get: function () {
  18415. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18416. },
  18417. enumerable: true,
  18418. configurable: true
  18419. });
  18420. Object.defineProperty(TransformNode.prototype, "up", {
  18421. /**
  18422. * The up direction of that transform in world space.
  18423. */
  18424. get: function () {
  18425. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18426. },
  18427. enumerable: true,
  18428. configurable: true
  18429. });
  18430. Object.defineProperty(TransformNode.prototype, "right", {
  18431. /**
  18432. * The right direction of that transform in world space.
  18433. */
  18434. get: function () {
  18435. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18436. },
  18437. enumerable: true,
  18438. configurable: true
  18439. });
  18440. /**
  18441. * Returns the latest update of the World matrix
  18442. * Returns a Matrix.
  18443. */
  18444. TransformNode.prototype.getWorldMatrix = function () {
  18445. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18446. this.computeWorldMatrix();
  18447. }
  18448. return this._worldMatrix;
  18449. };
  18450. /** @hidden */
  18451. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18452. return this._worldMatrixDeterminant;
  18453. };
  18454. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18455. /**
  18456. * Returns directly the latest state of the mesh World matrix.
  18457. * A Matrix is returned.
  18458. */
  18459. get: function () {
  18460. return this._worldMatrix;
  18461. },
  18462. enumerable: true,
  18463. configurable: true
  18464. });
  18465. /**
  18466. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18467. * Returns the TransformNode.
  18468. */
  18469. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18470. this._poseMatrix.copyFrom(matrix);
  18471. return this;
  18472. };
  18473. /**
  18474. * Returns the mesh Pose matrix.
  18475. * Returned object : Matrix
  18476. */
  18477. TransformNode.prototype.getPoseMatrix = function () {
  18478. return this._poseMatrix;
  18479. };
  18480. TransformNode.prototype._isSynchronized = function () {
  18481. if (this._isDirty) {
  18482. return false;
  18483. }
  18484. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18485. return false;
  18486. if (this._cache.pivotMatrixUpdated) {
  18487. return false;
  18488. }
  18489. if (this.infiniteDistance) {
  18490. return false;
  18491. }
  18492. if (!this._cache.position.equals(this.position))
  18493. return false;
  18494. if (this.rotationQuaternion) {
  18495. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18496. return false;
  18497. }
  18498. if (!this._cache.rotation.equals(this.rotation))
  18499. return false;
  18500. if (!this._cache.scaling.equals(this.scaling))
  18501. return false;
  18502. return true;
  18503. };
  18504. TransformNode.prototype._initCache = function () {
  18505. _super.prototype._initCache.call(this);
  18506. this._cache.localMatrixUpdated = false;
  18507. this._cache.position = BABYLON.Vector3.Zero();
  18508. this._cache.scaling = BABYLON.Vector3.Zero();
  18509. this._cache.rotation = BABYLON.Vector3.Zero();
  18510. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18511. this._cache.billboardMode = -1;
  18512. };
  18513. TransformNode.prototype.markAsDirty = function (property) {
  18514. if (property === "rotation") {
  18515. this.rotationQuaternion = null;
  18516. }
  18517. this._currentRenderId = Number.MAX_VALUE;
  18518. this._isDirty = true;
  18519. return this;
  18520. };
  18521. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18522. /**
  18523. * Returns the current mesh absolute position.
  18524. * Retuns a Vector3.
  18525. */
  18526. get: function () {
  18527. return this._absolutePosition;
  18528. },
  18529. enumerable: true,
  18530. configurable: true
  18531. });
  18532. /**
  18533. * Sets a new matrix to apply before all other transformation
  18534. * @param matrix defines the transform matrix
  18535. * @returns the current TransformNode
  18536. */
  18537. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18538. return this.setPivotMatrix(matrix, false);
  18539. };
  18540. /**
  18541. * Sets a new pivot matrix to the current node
  18542. * @param matrix defines the new pivot matrix to use
  18543. * @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
  18544. * @returns the current TransformNode
  18545. */
  18546. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18547. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18548. this._pivotMatrix = matrix.clone();
  18549. this._cache.pivotMatrixUpdated = true;
  18550. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18551. if (this._postMultiplyPivotMatrix) {
  18552. if (!this._pivotMatrixInverse) {
  18553. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18554. }
  18555. else {
  18556. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18557. }
  18558. }
  18559. return this;
  18560. };
  18561. /**
  18562. * Returns the mesh pivot matrix.
  18563. * Default : Identity.
  18564. * A Matrix is returned.
  18565. */
  18566. TransformNode.prototype.getPivotMatrix = function () {
  18567. return this._pivotMatrix;
  18568. };
  18569. /**
  18570. * Prevents the World matrix to be computed any longer.
  18571. * Returns the TransformNode.
  18572. */
  18573. TransformNode.prototype.freezeWorldMatrix = function () {
  18574. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18575. this.computeWorldMatrix(true);
  18576. this._isWorldMatrixFrozen = true;
  18577. return this;
  18578. };
  18579. /**
  18580. * Allows back the World matrix computation.
  18581. * Returns the TransformNode.
  18582. */
  18583. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18584. this._isWorldMatrixFrozen = false;
  18585. this.computeWorldMatrix(true);
  18586. return this;
  18587. };
  18588. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18589. /**
  18590. * True if the World matrix has been frozen.
  18591. * Returns a boolean.
  18592. */
  18593. get: function () {
  18594. return this._isWorldMatrixFrozen;
  18595. },
  18596. enumerable: true,
  18597. configurable: true
  18598. });
  18599. /**
  18600. * Retuns the mesh absolute position in the World.
  18601. * Returns a Vector3.
  18602. */
  18603. TransformNode.prototype.getAbsolutePosition = function () {
  18604. this.computeWorldMatrix();
  18605. return this._absolutePosition;
  18606. };
  18607. /**
  18608. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18609. * Returns the TransformNode.
  18610. */
  18611. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18612. if (!absolutePosition) {
  18613. return this;
  18614. }
  18615. var absolutePositionX;
  18616. var absolutePositionY;
  18617. var absolutePositionZ;
  18618. if (absolutePosition.x === undefined) {
  18619. if (arguments.length < 3) {
  18620. return this;
  18621. }
  18622. absolutePositionX = arguments[0];
  18623. absolutePositionY = arguments[1];
  18624. absolutePositionZ = arguments[2];
  18625. }
  18626. else {
  18627. absolutePositionX = absolutePosition.x;
  18628. absolutePositionY = absolutePosition.y;
  18629. absolutePositionZ = absolutePosition.z;
  18630. }
  18631. if (this.parent) {
  18632. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18633. invertParentWorldMatrix.invert();
  18634. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18635. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18636. }
  18637. else {
  18638. this.position.x = absolutePositionX;
  18639. this.position.y = absolutePositionY;
  18640. this.position.z = absolutePositionZ;
  18641. }
  18642. return this;
  18643. };
  18644. /**
  18645. * Sets the mesh position in its local space.
  18646. * Returns the TransformNode.
  18647. */
  18648. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18649. this.computeWorldMatrix();
  18650. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18651. return this;
  18652. };
  18653. /**
  18654. * Returns the mesh position in the local space from the current World matrix values.
  18655. * Returns a new Vector3.
  18656. */
  18657. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18658. this.computeWorldMatrix();
  18659. var invLocalWorldMatrix = this._localWorld.clone();
  18660. invLocalWorldMatrix.invert();
  18661. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18662. };
  18663. /**
  18664. * Translates the mesh along the passed Vector3 in its local space.
  18665. * Returns the TransformNode.
  18666. */
  18667. TransformNode.prototype.locallyTranslate = function (vector3) {
  18668. this.computeWorldMatrix(true);
  18669. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18670. return this;
  18671. };
  18672. /**
  18673. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18674. * @param targetPoint the position (must be in same space as current mesh) to look at
  18675. * @param yawCor optional yaw (y-axis) correction in radians
  18676. * @param pitchCor optional pitch (x-axis) correction in radians
  18677. * @param rollCor optional roll (z-axis) correction in radians
  18678. * @param space the choosen space of the target
  18679. * @returns the TransformNode.
  18680. */
  18681. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18682. if (yawCor === void 0) { yawCor = 0; }
  18683. if (pitchCor === void 0) { pitchCor = 0; }
  18684. if (rollCor === void 0) { rollCor = 0; }
  18685. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18686. var dv = TransformNode._lookAtVectorCache;
  18687. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18688. targetPoint.subtractToRef(pos, dv);
  18689. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18690. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18691. var pitch = Math.atan2(dv.y, len);
  18692. if (this.rotationQuaternion) {
  18693. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18694. }
  18695. else {
  18696. this.rotation.x = pitch + pitchCor;
  18697. this.rotation.y = yaw + yawCor;
  18698. this.rotation.z = rollCor;
  18699. }
  18700. return this;
  18701. };
  18702. /**
  18703. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18704. * This Vector3 is expressed in the World space.
  18705. */
  18706. TransformNode.prototype.getDirection = function (localAxis) {
  18707. var result = BABYLON.Vector3.Zero();
  18708. this.getDirectionToRef(localAxis, result);
  18709. return result;
  18710. };
  18711. /**
  18712. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18713. * localAxis is expressed in the mesh local space.
  18714. * result is computed in the Wordl space from the mesh World matrix.
  18715. * Returns the TransformNode.
  18716. */
  18717. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18718. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18719. return this;
  18720. };
  18721. /**
  18722. * Sets a new pivot point to the current node
  18723. * @param point defines the new pivot point to use
  18724. * @param space defines if the point is in world or local space (local by default)
  18725. * @returns the current TransformNode
  18726. */
  18727. TransformNode.prototype.setPivotPoint = function (point, space) {
  18728. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18729. if (this.getScene().getRenderId() == 0) {
  18730. this.computeWorldMatrix(true);
  18731. }
  18732. var wm = this.getWorldMatrix();
  18733. if (space == BABYLON.Space.WORLD) {
  18734. var tmat = BABYLON.Tmp.Matrix[0];
  18735. wm.invertToRef(tmat);
  18736. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18737. }
  18738. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18739. };
  18740. /**
  18741. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18742. */
  18743. TransformNode.prototype.getPivotPoint = function () {
  18744. var point = BABYLON.Vector3.Zero();
  18745. this.getPivotPointToRef(point);
  18746. return point;
  18747. };
  18748. /**
  18749. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18750. * Returns the TransformNode.
  18751. */
  18752. TransformNode.prototype.getPivotPointToRef = function (result) {
  18753. result.x = -this._pivotMatrix.m[12];
  18754. result.y = -this._pivotMatrix.m[13];
  18755. result.z = -this._pivotMatrix.m[14];
  18756. return this;
  18757. };
  18758. /**
  18759. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18760. */
  18761. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18762. var point = BABYLON.Vector3.Zero();
  18763. this.getAbsolutePivotPointToRef(point);
  18764. return point;
  18765. };
  18766. /**
  18767. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18768. * Returns the TransformNode.
  18769. */
  18770. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18771. result.x = this._pivotMatrix.m[12];
  18772. result.y = this._pivotMatrix.m[13];
  18773. result.z = this._pivotMatrix.m[14];
  18774. this.getPivotPointToRef(result);
  18775. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18776. return this;
  18777. };
  18778. /**
  18779. * Defines the passed node as the parent of the current node.
  18780. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18781. * Returns the TransformNode.
  18782. */
  18783. TransformNode.prototype.setParent = function (node) {
  18784. if (node === null) {
  18785. var rotation = BABYLON.Tmp.Quaternion[0];
  18786. var position = BABYLON.Tmp.Vector3[0];
  18787. var scale = BABYLON.Tmp.Vector3[1];
  18788. if (this.parent && this.parent.computeWorldMatrix) {
  18789. this.parent.computeWorldMatrix(true);
  18790. }
  18791. this.computeWorldMatrix(true);
  18792. this.getWorldMatrix().decompose(scale, rotation, position);
  18793. if (this.rotationQuaternion) {
  18794. this.rotationQuaternion.copyFrom(rotation);
  18795. }
  18796. else {
  18797. rotation.toEulerAnglesToRef(this.rotation);
  18798. }
  18799. this.scaling.x = scale.x;
  18800. this.scaling.y = scale.y;
  18801. this.scaling.z = scale.z;
  18802. this.position.x = position.x;
  18803. this.position.y = position.y;
  18804. this.position.z = position.z;
  18805. }
  18806. else {
  18807. var rotation = BABYLON.Tmp.Quaternion[0];
  18808. var position = BABYLON.Tmp.Vector3[0];
  18809. var scale = BABYLON.Tmp.Vector3[1];
  18810. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18811. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18812. this.computeWorldMatrix(true);
  18813. node.computeWorldMatrix(true);
  18814. node.getWorldMatrix().invertToRef(invParentMatrix);
  18815. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18816. diffMatrix.decompose(scale, rotation, position);
  18817. if (this.rotationQuaternion) {
  18818. this.rotationQuaternion.copyFrom(rotation);
  18819. }
  18820. else {
  18821. rotation.toEulerAnglesToRef(this.rotation);
  18822. }
  18823. this.position.x = position.x;
  18824. this.position.y = position.y;
  18825. this.position.z = position.z;
  18826. this.scaling.x = scale.x;
  18827. this.scaling.y = scale.y;
  18828. this.scaling.z = scale.z;
  18829. }
  18830. this.parent = node;
  18831. return this;
  18832. };
  18833. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18834. get: function () {
  18835. return this._nonUniformScaling;
  18836. },
  18837. enumerable: true,
  18838. configurable: true
  18839. });
  18840. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18841. if (this._nonUniformScaling === value) {
  18842. return false;
  18843. }
  18844. this._nonUniformScaling = true;
  18845. return true;
  18846. };
  18847. /**
  18848. * Attach the current TransformNode to another TransformNode associated with a bone
  18849. * @param bone Bone affecting the TransformNode
  18850. * @param affectedTransformNode TransformNode associated with the bone
  18851. */
  18852. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18853. this._transformToBoneReferal = affectedTransformNode;
  18854. this.parent = bone;
  18855. if (bone.getWorldMatrix().determinant() < 0) {
  18856. this.scalingDeterminant *= -1;
  18857. }
  18858. return this;
  18859. };
  18860. TransformNode.prototype.detachFromBone = function () {
  18861. if (!this.parent) {
  18862. return this;
  18863. }
  18864. if (this.parent.getWorldMatrix().determinant() < 0) {
  18865. this.scalingDeterminant *= -1;
  18866. }
  18867. this._transformToBoneReferal = null;
  18868. this.parent = null;
  18869. return this;
  18870. };
  18871. /**
  18872. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18873. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18874. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18875. * The passed axis is also normalized.
  18876. * Returns the TransformNode.
  18877. */
  18878. TransformNode.prototype.rotate = function (axis, amount, space) {
  18879. axis.normalize();
  18880. if (!this.rotationQuaternion) {
  18881. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18882. this.rotation = BABYLON.Vector3.Zero();
  18883. }
  18884. var rotationQuaternion;
  18885. if (!space || space === BABYLON.Space.LOCAL) {
  18886. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18887. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18888. }
  18889. else {
  18890. if (this.parent) {
  18891. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18892. invertParentWorldMatrix.invert();
  18893. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18894. }
  18895. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18896. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18897. }
  18898. return this;
  18899. };
  18900. /**
  18901. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18902. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18903. * The passed axis is also normalized.
  18904. * Returns the TransformNode.
  18905. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18906. */
  18907. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18908. axis.normalize();
  18909. if (!this.rotationQuaternion) {
  18910. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18911. this.rotation.copyFromFloats(0, 0, 0);
  18912. }
  18913. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18914. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18915. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18916. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18917. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18918. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18919. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18920. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18921. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18922. return this;
  18923. };
  18924. /**
  18925. * Translates the mesh along the axis vector for the passed distance in the given space.
  18926. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18927. * Returns the TransformNode.
  18928. */
  18929. TransformNode.prototype.translate = function (axis, distance, space) {
  18930. var displacementVector = axis.scale(distance);
  18931. if (!space || space === BABYLON.Space.LOCAL) {
  18932. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18933. this.setPositionWithLocalVector(tempV3);
  18934. }
  18935. else {
  18936. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18937. }
  18938. return this;
  18939. };
  18940. /**
  18941. * Adds a rotation step to the mesh current rotation.
  18942. * x, y, z are Euler angles expressed in radians.
  18943. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18944. * This means this rotation is made in the mesh local space only.
  18945. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18946. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18947. * ```javascript
  18948. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18949. * ```
  18950. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18951. * 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.
  18952. * Returns the TransformNode.
  18953. */
  18954. TransformNode.prototype.addRotation = function (x, y, z) {
  18955. var rotationQuaternion;
  18956. if (this.rotationQuaternion) {
  18957. rotationQuaternion = this.rotationQuaternion;
  18958. }
  18959. else {
  18960. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18961. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18962. }
  18963. var accumulation = BABYLON.Tmp.Quaternion[0];
  18964. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18965. rotationQuaternion.multiplyInPlace(accumulation);
  18966. if (!this.rotationQuaternion) {
  18967. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18968. }
  18969. return this;
  18970. };
  18971. /**
  18972. * Computes the mesh World matrix and returns it.
  18973. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18974. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18975. * If the parameter `force`is set to `true`, the actual computation is done.
  18976. * Returns the mesh World Matrix.
  18977. */
  18978. TransformNode.prototype.computeWorldMatrix = function (force) {
  18979. if (this._isWorldMatrixFrozen) {
  18980. return this._worldMatrix;
  18981. }
  18982. if (!force && this.isSynchronized(true)) {
  18983. this._currentRenderId = this.getScene().getRenderId();
  18984. return this._worldMatrix;
  18985. }
  18986. this._cache.position.copyFrom(this.position);
  18987. this._cache.scaling.copyFrom(this.scaling);
  18988. this._cache.pivotMatrixUpdated = false;
  18989. this._cache.billboardMode = this.billboardMode;
  18990. this._currentRenderId = this.getScene().getRenderId();
  18991. this._childRenderId = this.getScene().getRenderId();
  18992. this._isDirty = false;
  18993. // Scaling
  18994. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18995. // Rotation
  18996. //rotate, if quaternion is set and rotation was used
  18997. if (this.rotationQuaternion) {
  18998. var len = this.rotation.length();
  18999. if (len) {
  19000. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19001. this.rotation.copyFromFloats(0, 0, 0);
  19002. }
  19003. }
  19004. if (this.rotationQuaternion) {
  19005. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19006. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19007. }
  19008. else {
  19009. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19010. this._cache.rotation.copyFrom(this.rotation);
  19011. }
  19012. // Translation
  19013. var camera = this.getScene().activeCamera;
  19014. if (this.infiniteDistance && !this.parent && camera) {
  19015. var cameraWorldMatrix = camera.getWorldMatrix();
  19016. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19017. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19018. }
  19019. else {
  19020. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19021. }
  19022. // Composing transformations
  19023. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19024. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19025. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19026. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19027. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19028. // Need to decompose each rotation here
  19029. var currentPosition = BABYLON.Tmp.Vector3[3];
  19030. if (this.parent && this.parent.getWorldMatrix) {
  19031. if (this._transformToBoneReferal) {
  19032. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19033. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19034. }
  19035. else {
  19036. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19037. }
  19038. }
  19039. else {
  19040. currentPosition.copyFrom(this.position);
  19041. }
  19042. currentPosition.subtractInPlace(camera.globalPosition);
  19043. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19044. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19045. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19046. }
  19047. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19048. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19049. }
  19050. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19051. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19052. }
  19053. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19054. }
  19055. else {
  19056. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19057. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19058. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19059. }
  19060. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19061. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19062. }
  19063. // Local world
  19064. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19065. // Parent
  19066. if (this.parent && this.parent.getWorldMatrix) {
  19067. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19068. if (this._transformToBoneReferal) {
  19069. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19070. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19071. }
  19072. else {
  19073. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19074. }
  19075. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19076. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19077. this._worldMatrix.copyFrom(this._localWorld);
  19078. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19079. }
  19080. else {
  19081. if (this._transformToBoneReferal) {
  19082. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19083. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19084. }
  19085. else {
  19086. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19087. }
  19088. }
  19089. this._markSyncedWithParent();
  19090. }
  19091. else {
  19092. this._worldMatrix.copyFrom(this._localWorld);
  19093. }
  19094. // Post multiply inverse of pivotMatrix
  19095. if (this._postMultiplyPivotMatrix) {
  19096. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19097. }
  19098. // Normal matrix
  19099. if (this.scaling.isNonUniform) {
  19100. this._updateNonUniformScalingState(true);
  19101. }
  19102. else if (this.parent && this.parent._nonUniformScaling) {
  19103. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19104. }
  19105. else {
  19106. this._updateNonUniformScalingState(false);
  19107. }
  19108. this._afterComputeWorldMatrix();
  19109. // Absolute position
  19110. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19111. // Callbacks
  19112. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19113. if (!this._poseMatrix) {
  19114. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19115. }
  19116. // Cache the determinant
  19117. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19118. return this._worldMatrix;
  19119. };
  19120. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19121. };
  19122. /**
  19123. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19124. * @param func: callback function to add
  19125. *
  19126. * Returns the TransformNode.
  19127. */
  19128. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19129. this.onAfterWorldMatrixUpdateObservable.add(func);
  19130. return this;
  19131. };
  19132. /**
  19133. * Removes a registered callback function.
  19134. * Returns the TransformNode.
  19135. */
  19136. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19137. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19138. return this;
  19139. };
  19140. /**
  19141. * Clone the current transform node
  19142. * Returns the new transform node
  19143. * @param name Name of the new clone
  19144. * @param newParent New parent for the clone
  19145. * @param doNotCloneChildren Do not clone children hierarchy
  19146. */
  19147. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19148. var _this = this;
  19149. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19150. result.name = name;
  19151. result.id = name;
  19152. if (newParent) {
  19153. result.parent = newParent;
  19154. }
  19155. if (!doNotCloneChildren) {
  19156. // Children
  19157. var directDescendants = this.getDescendants(true);
  19158. for (var index = 0; index < directDescendants.length; index++) {
  19159. var child = directDescendants[index];
  19160. if (child.clone) {
  19161. child.clone(name + "." + child.name, result);
  19162. }
  19163. }
  19164. }
  19165. return result;
  19166. };
  19167. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19168. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19169. serializationObject.type = this.getClassName();
  19170. // Parent
  19171. if (this.parent) {
  19172. serializationObject.parentId = this.parent.id;
  19173. }
  19174. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19175. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19176. }
  19177. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19178. serializationObject.isEnabled = this.isEnabled();
  19179. // Parent
  19180. if (this.parent) {
  19181. serializationObject.parentId = this.parent.id;
  19182. }
  19183. return serializationObject;
  19184. };
  19185. // Statics
  19186. /**
  19187. * Returns a new TransformNode object parsed from the source provided.
  19188. * The parameter `parsedMesh` is the source.
  19189. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19190. */
  19191. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19192. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19193. if (BABYLON.Tags) {
  19194. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19195. }
  19196. if (parsedTransformNode.localMatrix) {
  19197. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19198. }
  19199. else if (parsedTransformNode.pivotMatrix) {
  19200. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19201. }
  19202. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19203. // Parent
  19204. if (parsedTransformNode.parentId) {
  19205. transformNode._waitingParentId = parsedTransformNode.parentId;
  19206. }
  19207. return transformNode;
  19208. };
  19209. /**
  19210. * Releases resources associated with this transform node.
  19211. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19212. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19213. */
  19214. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19215. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19216. // Animations
  19217. this.getScene().stopAnimation(this);
  19218. // Remove from scene
  19219. this.getScene().removeTransformNode(this);
  19220. this.onAfterWorldMatrixUpdateObservable.clear();
  19221. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19222. };
  19223. // Statics
  19224. TransformNode.BILLBOARDMODE_NONE = 0;
  19225. TransformNode.BILLBOARDMODE_X = 1;
  19226. TransformNode.BILLBOARDMODE_Y = 2;
  19227. TransformNode.BILLBOARDMODE_Z = 4;
  19228. TransformNode.BILLBOARDMODE_ALL = 7;
  19229. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19230. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19231. __decorate([
  19232. BABYLON.serializeAsVector3()
  19233. ], TransformNode.prototype, "_rotation", void 0);
  19234. __decorate([
  19235. BABYLON.serializeAsQuaternion()
  19236. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19237. __decorate([
  19238. BABYLON.serializeAsVector3()
  19239. ], TransformNode.prototype, "_scaling", void 0);
  19240. __decorate([
  19241. BABYLON.serialize()
  19242. ], TransformNode.prototype, "billboardMode", void 0);
  19243. __decorate([
  19244. BABYLON.serialize()
  19245. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19246. __decorate([
  19247. BABYLON.serialize()
  19248. ], TransformNode.prototype, "infiniteDistance", void 0);
  19249. __decorate([
  19250. BABYLON.serializeAsVector3()
  19251. ], TransformNode.prototype, "position", void 0);
  19252. return TransformNode;
  19253. }(BABYLON.Node));
  19254. BABYLON.TransformNode = TransformNode;
  19255. })(BABYLON || (BABYLON = {}));
  19256. //# sourceMappingURL=babylon.transformNode.js.map
  19257. var BABYLON;
  19258. (function (BABYLON) {
  19259. /**
  19260. * Class used to store all common mesh properties
  19261. */
  19262. var AbstractMesh = /** @class */ (function (_super) {
  19263. __extends(AbstractMesh, _super);
  19264. // Constructor
  19265. /**
  19266. * Creates a new AbstractMesh
  19267. * @param name defines the name of the mesh
  19268. * @param scene defines the hosting scene
  19269. */
  19270. function AbstractMesh(name, scene) {
  19271. if (scene === void 0) { scene = null; }
  19272. var _this = _super.call(this, name, scene, false) || this;
  19273. _this._facetNb = 0; // facet number
  19274. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19275. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19276. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19277. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19278. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19279. _this._subDiv = {
  19280. max: 1,
  19281. X: 1,
  19282. Y: 1,
  19283. Z: 1
  19284. };
  19285. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19286. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19287. // Events
  19288. /**
  19289. * An event triggered when this mesh collides with another one
  19290. */
  19291. _this.onCollideObservable = new BABYLON.Observable();
  19292. /**
  19293. * An event triggered when the collision's position changes
  19294. */
  19295. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19296. /**
  19297. * An event triggered when material is changed
  19298. */
  19299. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19300. // Properties
  19301. /**
  19302. * Gets or sets the orientation for POV movement & rotation
  19303. */
  19304. _this.definedFacingForward = true;
  19305. /**
  19306. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19307. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19308. * * 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.
  19309. * @see http://doc.babylonjs.com/features/occlusionquery
  19310. */
  19311. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19312. /**
  19313. * 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:
  19314. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19315. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19316. * * 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.
  19317. * @see http://doc.babylonjs.com/features/occlusionquery
  19318. */
  19319. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19320. /**
  19321. * 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.
  19322. * The default value is -1 which means don't break the query and wait till the result
  19323. * @see http://doc.babylonjs.com/features/occlusionquery
  19324. */
  19325. _this.occlusionRetryCount = -1;
  19326. _this._occlusionInternalRetryCounter = 0;
  19327. _this._isOccluded = false;
  19328. _this._isOcclusionQueryInProgress = false;
  19329. _this._visibility = 1.0;
  19330. /** Gets or sets the alpha index used to sort transparent meshes
  19331. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19332. */
  19333. _this.alphaIndex = Number.MAX_VALUE;
  19334. /**
  19335. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19336. */
  19337. _this.isVisible = true;
  19338. /**
  19339. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19340. */
  19341. _this.isPickable = true;
  19342. /**
  19343. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19344. */
  19345. _this.showBoundingBox = false;
  19346. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19347. _this.showSubMeshesBoundingBox = false;
  19348. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19349. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19350. */
  19351. _this.isBlocker = false;
  19352. /**
  19353. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19354. */
  19355. _this.enablePointerMoveEvents = false;
  19356. /**
  19357. * Specifies the rendering group id for this mesh (0 by default)
  19358. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19359. */
  19360. _this.renderingGroupId = 0;
  19361. _this._receiveShadows = false;
  19362. /**
  19363. * Gets or sets a boolean indicating if the outline must be rendered as well
  19364. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19365. */
  19366. _this.renderOutline = false;
  19367. /** Defines color to use when rendering outline */
  19368. _this.outlineColor = BABYLON.Color3.Red();
  19369. /** Define width to use when rendering outline */
  19370. _this.outlineWidth = 0.02;
  19371. /**
  19372. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19373. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19374. */
  19375. _this.renderOverlay = false;
  19376. /** Defines color to use when rendering overlay */
  19377. _this.overlayColor = BABYLON.Color3.Red();
  19378. /** Defines alpha to use when rendering overlay */
  19379. _this.overlayAlpha = 0.5;
  19380. _this._hasVertexAlpha = false;
  19381. _this._useVertexColors = true;
  19382. _this._computeBonesUsingShaders = true;
  19383. _this._numBoneInfluencers = 4;
  19384. _this._applyFog = true;
  19385. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19386. _this.useOctreeForRenderingSelection = true;
  19387. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19388. _this.useOctreeForPicking = true;
  19389. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19390. _this.useOctreeForCollisions = true;
  19391. _this._layerMask = 0x0FFFFFFF;
  19392. /**
  19393. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19394. */
  19395. _this.alwaysSelectAsActiveMesh = false;
  19396. /**
  19397. * Gets or sets the current action manager
  19398. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19399. */
  19400. _this.actionManager = null;
  19401. /**
  19402. * Gets or sets impostor used for physic simulation
  19403. * @see http://doc.babylonjs.com/features/physics_engine
  19404. */
  19405. _this.physicsImpostor = null;
  19406. // Collisions
  19407. _this._checkCollisions = false;
  19408. _this._collisionMask = -1;
  19409. _this._collisionGroup = -1;
  19410. /**
  19411. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19412. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19413. */
  19414. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19415. /**
  19416. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19417. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19418. */
  19419. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19420. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19421. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19422. // Edges
  19423. /**
  19424. * Defines edge width used when edgesRenderer is enabled
  19425. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19426. */
  19427. _this.edgesWidth = 1;
  19428. /**
  19429. * Defines edge color used when edgesRenderer is enabled
  19430. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19431. */
  19432. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19433. // Cache
  19434. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19435. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19436. /** @hidden */
  19437. _this._renderId = 0;
  19438. /** @hidden */
  19439. _this._intersectionsInProgress = new Array();
  19440. /** @hidden */
  19441. _this._unIndexed = false;
  19442. /** @hidden */
  19443. _this._lightSources = new Array();
  19444. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19445. if (collidedMesh === void 0) { collidedMesh = null; }
  19446. //TODO move this to the collision coordinator!
  19447. if (_this.getScene().workerCollisions)
  19448. newPosition.multiplyInPlace(_this._collider._radius);
  19449. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19450. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19451. _this.position.addInPlace(_this._diffPositionForCollisions);
  19452. }
  19453. if (collidedMesh) {
  19454. _this.onCollideObservable.notifyObservers(collidedMesh);
  19455. }
  19456. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19457. };
  19458. _this.getScene().addMesh(_this);
  19459. _this._resyncLightSources();
  19460. return _this;
  19461. }
  19462. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19463. /**
  19464. * No billboard
  19465. */
  19466. get: function () {
  19467. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19468. },
  19469. enumerable: true,
  19470. configurable: true
  19471. });
  19472. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19473. /** Billboard on X axis */
  19474. get: function () {
  19475. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19476. },
  19477. enumerable: true,
  19478. configurable: true
  19479. });
  19480. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19481. /** Billboard on Y axis */
  19482. get: function () {
  19483. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19484. },
  19485. enumerable: true,
  19486. configurable: true
  19487. });
  19488. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19489. /** Billboard on Z axis */
  19490. get: function () {
  19491. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19492. },
  19493. enumerable: true,
  19494. configurable: true
  19495. });
  19496. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19497. /** Billboard on all axes */
  19498. get: function () {
  19499. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19500. },
  19501. enumerable: true,
  19502. configurable: true
  19503. });
  19504. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19505. /**
  19506. * Gets the number of facets in the mesh
  19507. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19508. */
  19509. get: function () {
  19510. return this._facetNb;
  19511. },
  19512. enumerable: true,
  19513. configurable: true
  19514. });
  19515. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19516. /**
  19517. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19518. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19519. */
  19520. get: function () {
  19521. return this._partitioningSubdivisions;
  19522. },
  19523. set: function (nb) {
  19524. this._partitioningSubdivisions = nb;
  19525. },
  19526. enumerable: true,
  19527. configurable: true
  19528. });
  19529. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19530. /**
  19531. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19532. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19533. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19534. */
  19535. get: function () {
  19536. return this._partitioningBBoxRatio;
  19537. },
  19538. set: function (ratio) {
  19539. this._partitioningBBoxRatio = ratio;
  19540. },
  19541. enumerable: true,
  19542. configurable: true
  19543. });
  19544. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19545. /**
  19546. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19547. * Works only for updatable meshes.
  19548. * Doesn't work with multi-materials
  19549. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19550. */
  19551. get: function () {
  19552. return this._facetDepthSort;
  19553. },
  19554. set: function (sort) {
  19555. this._facetDepthSort = sort;
  19556. },
  19557. enumerable: true,
  19558. configurable: true
  19559. });
  19560. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19561. /**
  19562. * The location (Vector3) where the facet depth sort must be computed from.
  19563. * By default, the active camera position.
  19564. * Used only when facet depth sort is enabled
  19565. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19566. */
  19567. get: function () {
  19568. return this._facetDepthSortFrom;
  19569. },
  19570. set: function (location) {
  19571. this._facetDepthSortFrom = location;
  19572. },
  19573. enumerable: true,
  19574. configurable: true
  19575. });
  19576. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19577. /**
  19578. * gets a boolean indicating if facetData is enabled
  19579. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19580. */
  19581. get: function () {
  19582. return this._facetDataEnabled;
  19583. },
  19584. enumerable: true,
  19585. configurable: true
  19586. });
  19587. /** @hidden */
  19588. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19589. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19590. return false;
  19591. }
  19592. this._markSubMeshesAsMiscDirty();
  19593. return true;
  19594. };
  19595. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19596. /** Set a function to call when this mesh collides with another one */
  19597. set: function (callback) {
  19598. if (this._onCollideObserver) {
  19599. this.onCollideObservable.remove(this._onCollideObserver);
  19600. }
  19601. this._onCollideObserver = this.onCollideObservable.add(callback);
  19602. },
  19603. enumerable: true,
  19604. configurable: true
  19605. });
  19606. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19607. /** Set a function to call when the collision's position changes */
  19608. set: function (callback) {
  19609. if (this._onCollisionPositionChangeObserver) {
  19610. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19611. }
  19612. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19613. },
  19614. enumerable: true,
  19615. configurable: true
  19616. });
  19617. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19618. /**
  19619. * 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
  19620. * @see http://doc.babylonjs.com/features/occlusionquery
  19621. */
  19622. get: function () {
  19623. return this._isOccluded;
  19624. },
  19625. set: function (value) {
  19626. this._isOccluded = value;
  19627. },
  19628. enumerable: true,
  19629. configurable: true
  19630. });
  19631. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19632. /**
  19633. * Flag to check the progress status of the query
  19634. * @see http://doc.babylonjs.com/features/occlusionquery
  19635. */
  19636. get: function () {
  19637. return this._isOcclusionQueryInProgress;
  19638. },
  19639. enumerable: true,
  19640. configurable: true
  19641. });
  19642. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19643. /**
  19644. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19645. */
  19646. get: function () {
  19647. return this._visibility;
  19648. },
  19649. /**
  19650. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19651. */
  19652. set: function (value) {
  19653. if (this._visibility === value) {
  19654. return;
  19655. }
  19656. this._visibility = value;
  19657. this._markSubMeshesAsMiscDirty();
  19658. },
  19659. enumerable: true,
  19660. configurable: true
  19661. });
  19662. Object.defineProperty(AbstractMesh.prototype, "material", {
  19663. /** Gets or sets current material */
  19664. get: function () {
  19665. return this._material;
  19666. },
  19667. set: function (value) {
  19668. if (this._material === value) {
  19669. return;
  19670. }
  19671. this._material = value;
  19672. if (this.onMaterialChangedObservable.hasObservers) {
  19673. this.onMaterialChangedObservable.notifyObservers(this);
  19674. }
  19675. if (!this.subMeshes) {
  19676. return;
  19677. }
  19678. this._unBindEffect();
  19679. },
  19680. enumerable: true,
  19681. configurable: true
  19682. });
  19683. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19684. /**
  19685. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19686. * @see http://doc.babylonjs.com/babylon101/shadows
  19687. */
  19688. get: function () {
  19689. return this._receiveShadows;
  19690. },
  19691. set: function (value) {
  19692. if (this._receiveShadows === value) {
  19693. return;
  19694. }
  19695. this._receiveShadows = value;
  19696. this._markSubMeshesAsLightDirty();
  19697. },
  19698. enumerable: true,
  19699. configurable: true
  19700. });
  19701. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19702. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19703. get: function () {
  19704. return this._hasVertexAlpha;
  19705. },
  19706. set: function (value) {
  19707. if (this._hasVertexAlpha === value) {
  19708. return;
  19709. }
  19710. this._hasVertexAlpha = value;
  19711. this._markSubMeshesAsAttributesDirty();
  19712. this._markSubMeshesAsMiscDirty();
  19713. },
  19714. enumerable: true,
  19715. configurable: true
  19716. });
  19717. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19718. /** 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) */
  19719. get: function () {
  19720. return this._useVertexColors;
  19721. },
  19722. set: function (value) {
  19723. if (this._useVertexColors === value) {
  19724. return;
  19725. }
  19726. this._useVertexColors = value;
  19727. this._markSubMeshesAsAttributesDirty();
  19728. },
  19729. enumerable: true,
  19730. configurable: true
  19731. });
  19732. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19733. /**
  19734. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19735. */
  19736. get: function () {
  19737. return this._computeBonesUsingShaders;
  19738. },
  19739. set: function (value) {
  19740. if (this._computeBonesUsingShaders === value) {
  19741. return;
  19742. }
  19743. this._computeBonesUsingShaders = value;
  19744. this._markSubMeshesAsAttributesDirty();
  19745. },
  19746. enumerable: true,
  19747. configurable: true
  19748. });
  19749. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19750. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19751. get: function () {
  19752. return this._numBoneInfluencers;
  19753. },
  19754. set: function (value) {
  19755. if (this._numBoneInfluencers === value) {
  19756. return;
  19757. }
  19758. this._numBoneInfluencers = value;
  19759. this._markSubMeshesAsAttributesDirty();
  19760. },
  19761. enumerable: true,
  19762. configurable: true
  19763. });
  19764. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19765. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19766. get: function () {
  19767. return this._applyFog;
  19768. },
  19769. set: function (value) {
  19770. if (this._applyFog === value) {
  19771. return;
  19772. }
  19773. this._applyFog = value;
  19774. this._markSubMeshesAsMiscDirty();
  19775. },
  19776. enumerable: true,
  19777. configurable: true
  19778. });
  19779. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19780. /**
  19781. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19782. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19783. */
  19784. get: function () {
  19785. return this._layerMask;
  19786. },
  19787. set: function (value) {
  19788. if (value === this._layerMask) {
  19789. return;
  19790. }
  19791. this._layerMask = value;
  19792. this._resyncLightSources();
  19793. },
  19794. enumerable: true,
  19795. configurable: true
  19796. });
  19797. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19798. /**
  19799. * Gets or sets a collision mask used to mask collisions (default is -1).
  19800. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19801. */
  19802. get: function () {
  19803. return this._collisionMask;
  19804. },
  19805. set: function (mask) {
  19806. this._collisionMask = !isNaN(mask) ? mask : -1;
  19807. },
  19808. enumerable: true,
  19809. configurable: true
  19810. });
  19811. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19812. /**
  19813. * Gets or sets the current collision group mask (-1 by default).
  19814. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19815. */
  19816. get: function () {
  19817. return this._collisionGroup;
  19818. },
  19819. set: function (mask) {
  19820. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19821. },
  19822. enumerable: true,
  19823. configurable: true
  19824. });
  19825. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19826. /** @hidden */
  19827. get: function () {
  19828. return null;
  19829. },
  19830. enumerable: true,
  19831. configurable: true
  19832. });
  19833. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19834. get: function () {
  19835. return this._skeleton;
  19836. },
  19837. /**
  19838. * Gets or sets a skeleton to apply skining transformations
  19839. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19840. */
  19841. set: function (value) {
  19842. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19843. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19844. }
  19845. if (value && value.needInitialSkinMatrix) {
  19846. value._registerMeshWithPoseMatrix(this);
  19847. }
  19848. this._skeleton = value;
  19849. if (!this._skeleton) {
  19850. this._bonesTransformMatrices = null;
  19851. }
  19852. this._markSubMeshesAsAttributesDirty();
  19853. },
  19854. enumerable: true,
  19855. configurable: true
  19856. });
  19857. /**
  19858. * Returns the string "AbstractMesh"
  19859. * @returns "AbstractMesh"
  19860. */
  19861. AbstractMesh.prototype.getClassName = function () {
  19862. return "AbstractMesh";
  19863. };
  19864. /**
  19865. * Gets a string representation of the current mesh
  19866. * @param fullDetails defines a boolean indicating if full details must be included
  19867. * @returns a string representation of the current mesh
  19868. */
  19869. AbstractMesh.prototype.toString = function (fullDetails) {
  19870. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19871. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19872. if (this._skeleton) {
  19873. ret += ", skeleton: " + this._skeleton.name;
  19874. }
  19875. if (fullDetails) {
  19876. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19877. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19878. }
  19879. return ret;
  19880. };
  19881. /** @hidden */
  19882. AbstractMesh.prototype._rebuild = function () {
  19883. if (this._occlusionQuery) {
  19884. this._occlusionQuery = null;
  19885. }
  19886. if (this._edgesRenderer) {
  19887. this._edgesRenderer._rebuild();
  19888. }
  19889. if (!this.subMeshes) {
  19890. return;
  19891. }
  19892. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19893. var subMesh = _a[_i];
  19894. subMesh._rebuild();
  19895. }
  19896. };
  19897. /** @hidden */
  19898. AbstractMesh.prototype._resyncLightSources = function () {
  19899. this._lightSources.length = 0;
  19900. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19901. var light = _a[_i];
  19902. if (!light.isEnabled()) {
  19903. continue;
  19904. }
  19905. if (light.canAffectMesh(this)) {
  19906. this._lightSources.push(light);
  19907. }
  19908. }
  19909. this._markSubMeshesAsLightDirty();
  19910. };
  19911. /** @hidden */
  19912. AbstractMesh.prototype._resyncLighSource = function (light) {
  19913. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19914. var index = this._lightSources.indexOf(light);
  19915. if (index === -1) {
  19916. if (!isIn) {
  19917. return;
  19918. }
  19919. this._lightSources.push(light);
  19920. }
  19921. else {
  19922. if (isIn) {
  19923. return;
  19924. }
  19925. this._lightSources.splice(index, 1);
  19926. }
  19927. this._markSubMeshesAsLightDirty();
  19928. };
  19929. /** @hidden */
  19930. AbstractMesh.prototype._unBindEffect = function () {
  19931. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19932. var subMesh = _a[_i];
  19933. subMesh.setEffect(null);
  19934. }
  19935. };
  19936. /** @hidden */
  19937. AbstractMesh.prototype._removeLightSource = function (light) {
  19938. var index = this._lightSources.indexOf(light);
  19939. if (index === -1) {
  19940. return;
  19941. }
  19942. this._lightSources.splice(index, 1);
  19943. this._markSubMeshesAsLightDirty();
  19944. };
  19945. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19946. if (!this.subMeshes) {
  19947. return;
  19948. }
  19949. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19950. var subMesh = _a[_i];
  19951. if (subMesh._materialDefines) {
  19952. func(subMesh._materialDefines);
  19953. }
  19954. }
  19955. };
  19956. /** @hidden */
  19957. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19958. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19959. };
  19960. /** @hidden */
  19961. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19962. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19963. };
  19964. /** @hidden */
  19965. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19966. if (!this.subMeshes) {
  19967. return;
  19968. }
  19969. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19970. var subMesh = _a[_i];
  19971. var material = subMesh.getMaterial();
  19972. if (material) {
  19973. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19974. }
  19975. }
  19976. };
  19977. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19978. /**
  19979. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19980. */
  19981. get: function () {
  19982. return this._scaling;
  19983. },
  19984. set: function (newScaling) {
  19985. this._scaling = newScaling;
  19986. if (this.physicsImpostor) {
  19987. this.physicsImpostor.forceUpdate();
  19988. }
  19989. },
  19990. enumerable: true,
  19991. configurable: true
  19992. });
  19993. // Methods
  19994. /**
  19995. * Disables the mesh edge rendering mode
  19996. * @returns the currentAbstractMesh
  19997. */
  19998. AbstractMesh.prototype.disableEdgesRendering = function () {
  19999. if (this._edgesRenderer) {
  20000. this._edgesRenderer.dispose();
  20001. this._edgesRenderer = null;
  20002. }
  20003. return this;
  20004. };
  20005. /**
  20006. * Enables the edge rendering mode on the mesh.
  20007. * This mode makes the mesh edges visible
  20008. * @param epsilon defines the maximal distance between two angles to detect a face
  20009. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20010. * @returns the currentAbstractMesh
  20011. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20012. */
  20013. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20014. if (epsilon === void 0) { epsilon = 0.95; }
  20015. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20016. this.disableEdgesRendering();
  20017. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20018. return this;
  20019. };
  20020. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20021. /**
  20022. * Returns true if the mesh is blocked. Implemented by child classes
  20023. */
  20024. get: function () {
  20025. return false;
  20026. },
  20027. enumerable: true,
  20028. configurable: true
  20029. });
  20030. /**
  20031. * Returns the mesh itself by default. Implemented by child classes
  20032. * @param camera defines the camera to use to pick the right LOD level
  20033. * @returns the currentAbstractMesh
  20034. */
  20035. AbstractMesh.prototype.getLOD = function (camera) {
  20036. return this;
  20037. };
  20038. /**
  20039. * Returns 0 by default. Implemented by child classes
  20040. * @returns an integer
  20041. */
  20042. AbstractMesh.prototype.getTotalVertices = function () {
  20043. return 0;
  20044. };
  20045. /**
  20046. * Returns null by default. Implemented by child classes
  20047. * @returns null
  20048. */
  20049. AbstractMesh.prototype.getIndices = function () {
  20050. return null;
  20051. };
  20052. /**
  20053. * Returns the array of the requested vertex data kind. Implemented by child classes
  20054. * @param kind defines the vertex data kind to use
  20055. * @returns null
  20056. */
  20057. AbstractMesh.prototype.getVerticesData = function (kind) {
  20058. return null;
  20059. };
  20060. /**
  20061. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20062. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20063. * Note that a new underlying VertexBuffer object is created each call.
  20064. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20065. * @param kind defines vertex data kind:
  20066. * * BABYLON.VertexBuffer.PositionKind
  20067. * * BABYLON.VertexBuffer.UVKind
  20068. * * BABYLON.VertexBuffer.UV2Kind
  20069. * * BABYLON.VertexBuffer.UV3Kind
  20070. * * BABYLON.VertexBuffer.UV4Kind
  20071. * * BABYLON.VertexBuffer.UV5Kind
  20072. * * BABYLON.VertexBuffer.UV6Kind
  20073. * * BABYLON.VertexBuffer.ColorKind
  20074. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20075. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20076. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20077. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20078. * @param data defines the data source
  20079. * @param updatable defines if the data must be flagged as updatable (or static)
  20080. * @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
  20081. * @returns the current mesh
  20082. */
  20083. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20084. return this;
  20085. };
  20086. /**
  20087. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20088. * If the mesh has no geometry, it is simply returned as it is.
  20089. * @param kind defines vertex data kind:
  20090. * * BABYLON.VertexBuffer.PositionKind
  20091. * * BABYLON.VertexBuffer.UVKind
  20092. * * BABYLON.VertexBuffer.UV2Kind
  20093. * * BABYLON.VertexBuffer.UV3Kind
  20094. * * BABYLON.VertexBuffer.UV4Kind
  20095. * * BABYLON.VertexBuffer.UV5Kind
  20096. * * BABYLON.VertexBuffer.UV6Kind
  20097. * * BABYLON.VertexBuffer.ColorKind
  20098. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20099. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20100. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20101. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20102. * @param data defines the data source
  20103. * @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
  20104. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20105. * @returns the current mesh
  20106. */
  20107. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20108. return this;
  20109. };
  20110. /**
  20111. * Sets the mesh indices,
  20112. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20113. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20114. * @param totalVertices Defines the total number of vertices
  20115. * @returns the current mesh
  20116. */
  20117. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20118. return this;
  20119. };
  20120. /**
  20121. * Gets a boolean indicating if specific vertex data is present
  20122. * @param kind defines the vertex data kind to use
  20123. * @returns true is data kind is present
  20124. */
  20125. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20126. return false;
  20127. };
  20128. /**
  20129. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20130. * @returns a BoundingInfo
  20131. */
  20132. AbstractMesh.prototype.getBoundingInfo = function () {
  20133. if (this._masterMesh) {
  20134. return this._masterMesh.getBoundingInfo();
  20135. }
  20136. if (!this._boundingInfo) {
  20137. // this._boundingInfo is being created here
  20138. this._updateBoundingInfo();
  20139. }
  20140. // cannot be null.
  20141. return this._boundingInfo;
  20142. };
  20143. /**
  20144. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20145. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20146. * @returns the current mesh
  20147. */
  20148. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20149. if (includeDescendants === void 0) { includeDescendants = true; }
  20150. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20151. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20152. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20153. if (maxDimension === 0) {
  20154. return this;
  20155. }
  20156. var scale = 1 / maxDimension;
  20157. this.scaling.scaleInPlace(scale);
  20158. return this;
  20159. };
  20160. /**
  20161. * Overwrite the current bounding info
  20162. * @param boundingInfo defines the new bounding info
  20163. * @returns the current mesh
  20164. */
  20165. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20166. this._boundingInfo = boundingInfo;
  20167. return this;
  20168. };
  20169. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20170. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20171. get: function () {
  20172. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20173. },
  20174. enumerable: true,
  20175. configurable: true
  20176. });
  20177. /** @hidden */
  20178. AbstractMesh.prototype._preActivate = function () {
  20179. };
  20180. /** @hidden */
  20181. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20182. };
  20183. /** @hidden */
  20184. AbstractMesh.prototype._activate = function (renderId) {
  20185. this._renderId = renderId;
  20186. };
  20187. /**
  20188. * Gets the current world matrix
  20189. * @returns a Matrix
  20190. */
  20191. AbstractMesh.prototype.getWorldMatrix = function () {
  20192. if (this._masterMesh) {
  20193. return this._masterMesh.getWorldMatrix();
  20194. }
  20195. return _super.prototype.getWorldMatrix.call(this);
  20196. };
  20197. /** @hidden */
  20198. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20199. if (this._masterMesh) {
  20200. return this._masterMesh._getWorldMatrixDeterminant();
  20201. }
  20202. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20203. };
  20204. // ================================== Point of View Movement =================================
  20205. /**
  20206. * Perform relative position change from the point of view of behind the front of the mesh.
  20207. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20208. * Supports definition of mesh facing forward or backward
  20209. * @param amountRight defines the distance on the right axis
  20210. * @param amountUp defines the distance on the up axis
  20211. * @param amountForward defines the distance on the forward axis
  20212. * @returns the current mesh
  20213. */
  20214. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20215. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20216. return this;
  20217. };
  20218. /**
  20219. * Calculate relative position change from the point of view of behind the front of the mesh.
  20220. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20221. * Supports definition of mesh facing forward or backward
  20222. * @param amountRight defines the distance on the right axis
  20223. * @param amountUp defines the distance on the up axis
  20224. * @param amountForward defines the distance on the forward axis
  20225. * @returns the new displacement vector
  20226. */
  20227. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20228. var rotMatrix = new BABYLON.Matrix();
  20229. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20230. rotQuaternion.toRotationMatrix(rotMatrix);
  20231. var translationDelta = BABYLON.Vector3.Zero();
  20232. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20233. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20234. return translationDelta;
  20235. };
  20236. // ================================== Point of View Rotation =================================
  20237. /**
  20238. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20239. * Supports definition of mesh facing forward or backward
  20240. * @param flipBack defines the flip
  20241. * @param twirlClockwise defines the twirl
  20242. * @param tiltRight defines the tilt
  20243. * @returns the current mesh
  20244. */
  20245. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20246. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20247. return this;
  20248. };
  20249. /**
  20250. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20251. * Supports definition of mesh facing forward or backward.
  20252. * @param flipBack defines the flip
  20253. * @param twirlClockwise defines the twirl
  20254. * @param tiltRight defines the tilt
  20255. * @returns the new rotation vector
  20256. */
  20257. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20258. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20259. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20260. };
  20261. /**
  20262. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20263. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20264. * @returns the new bounding vectors
  20265. */
  20266. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20267. if (includeDescendants === void 0) { includeDescendants = true; }
  20268. // Ensures that all world matrix will be recomputed.
  20269. this.getScene().incrementRenderId();
  20270. this.computeWorldMatrix(true);
  20271. var min;
  20272. var max;
  20273. var boundingInfo = this.getBoundingInfo();
  20274. if (!this.subMeshes) {
  20275. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20276. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20277. }
  20278. else {
  20279. min = boundingInfo.boundingBox.minimumWorld;
  20280. max = boundingInfo.boundingBox.maximumWorld;
  20281. }
  20282. if (includeDescendants) {
  20283. var descendants = this.getDescendants(false);
  20284. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20285. var descendant = descendants_1[_i];
  20286. var childMesh = descendant;
  20287. childMesh.computeWorldMatrix(true);
  20288. //make sure we have the needed params to get mix and max
  20289. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20290. continue;
  20291. }
  20292. var childBoundingInfo = childMesh.getBoundingInfo();
  20293. var boundingBox = childBoundingInfo.boundingBox;
  20294. var minBox = boundingBox.minimumWorld;
  20295. var maxBox = boundingBox.maximumWorld;
  20296. BABYLON.Tools.CheckExtends(minBox, min, max);
  20297. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20298. }
  20299. }
  20300. return {
  20301. min: min,
  20302. max: max
  20303. };
  20304. };
  20305. /** @hidden */
  20306. AbstractMesh.prototype._updateBoundingInfo = function () {
  20307. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20308. this._boundingInfo.update(this.worldMatrixFromCache);
  20309. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20310. return this;
  20311. };
  20312. /** @hidden */
  20313. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20314. if (!this.subMeshes) {
  20315. return this;
  20316. }
  20317. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20318. var subMesh = this.subMeshes[subIndex];
  20319. if (!subMesh.IsGlobal) {
  20320. subMesh.updateBoundingInfo(matrix);
  20321. }
  20322. }
  20323. return this;
  20324. };
  20325. /** @hidden */
  20326. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20327. // Bounding info
  20328. this._updateBoundingInfo();
  20329. };
  20330. /**
  20331. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20332. * A mesh is in the frustum if its bounding box intersects the frustum
  20333. * @param frustumPlanes defines the frustum to test
  20334. * @returns true if the mesh is in the frustum planes
  20335. */
  20336. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20337. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20338. };
  20339. /**
  20340. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20341. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20342. * @param frustumPlanes defines the frustum to test
  20343. * @returns true if the mesh is completely in the frustum planes
  20344. */
  20345. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20346. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20347. };
  20348. /**
  20349. * True if the mesh intersects another mesh or a SolidParticle object
  20350. * @param mesh defines a target mesh or SolidParticle to test
  20351. * @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)
  20352. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20353. * @returns true if there is an intersection
  20354. */
  20355. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20356. if (precise === void 0) { precise = false; }
  20357. if (!this._boundingInfo || !mesh._boundingInfo) {
  20358. return false;
  20359. }
  20360. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20361. return true;
  20362. }
  20363. if (includeDescendants) {
  20364. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20365. var child = _a[_i];
  20366. if (child.intersectsMesh(mesh, precise, true)) {
  20367. return true;
  20368. }
  20369. }
  20370. }
  20371. return false;
  20372. };
  20373. /**
  20374. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20375. * @param point defines the point to test
  20376. * @returns true if there is an intersection
  20377. */
  20378. AbstractMesh.prototype.intersectsPoint = function (point) {
  20379. if (!this._boundingInfo) {
  20380. return false;
  20381. }
  20382. return this._boundingInfo.intersectsPoint(point);
  20383. };
  20384. /**
  20385. * Gets the current physics impostor
  20386. * @see http://doc.babylonjs.com/features/physics_engine
  20387. * @returns a physics impostor or null
  20388. */
  20389. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20390. return this.physicsImpostor;
  20391. };
  20392. /**
  20393. * Gets the position of the current mesh in camera space
  20394. * @param camera defines the camera to use
  20395. * @returns a position
  20396. */
  20397. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20398. if (camera === void 0) { camera = null; }
  20399. if (!camera) {
  20400. camera = this.getScene().activeCamera;
  20401. }
  20402. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20403. };
  20404. /**
  20405. * Returns the distance from the mesh to the active camera
  20406. * @param camera defines the camera to use
  20407. * @returns the distance
  20408. */
  20409. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20410. if (camera === void 0) { camera = null; }
  20411. if (!camera) {
  20412. camera = this.getScene().activeCamera;
  20413. }
  20414. return this.absolutePosition.subtract(camera.position).length();
  20415. };
  20416. /**
  20417. * Apply a physic impulse to the mesh
  20418. * @param force defines the force to apply
  20419. * @param contactPoint defines where to apply the force
  20420. * @returns the current mesh
  20421. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20422. */
  20423. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20424. if (!this.physicsImpostor) {
  20425. return this;
  20426. }
  20427. this.physicsImpostor.applyImpulse(force, contactPoint);
  20428. return this;
  20429. };
  20430. /**
  20431. * Creates a physic joint between two meshes
  20432. * @param otherMesh defines the other mesh to use
  20433. * @param pivot1 defines the pivot to use on this mesh
  20434. * @param pivot2 defines the pivot to use on the other mesh
  20435. * @param options defines additional options (can be plugin dependent)
  20436. * @returns the current mesh
  20437. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20438. */
  20439. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20440. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20441. return this;
  20442. }
  20443. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20444. mainPivot: pivot1,
  20445. connectedPivot: pivot2,
  20446. nativeParams: options
  20447. });
  20448. return this;
  20449. };
  20450. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20451. // Collisions
  20452. /**
  20453. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20454. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20455. */
  20456. get: function () {
  20457. return this._checkCollisions;
  20458. },
  20459. set: function (collisionEnabled) {
  20460. this._checkCollisions = collisionEnabled;
  20461. if (this.getScene().workerCollisions) {
  20462. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20463. }
  20464. },
  20465. enumerable: true,
  20466. configurable: true
  20467. });
  20468. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20469. /**
  20470. * Gets Collider object used to compute collisions (not physics)
  20471. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20472. */
  20473. get: function () {
  20474. return this._collider;
  20475. },
  20476. enumerable: true,
  20477. configurable: true
  20478. });
  20479. /**
  20480. * Move the mesh using collision engine
  20481. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20482. * @param displacement defines the requested displacement vector
  20483. * @returns the current mesh
  20484. */
  20485. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20486. var globalPosition = this.getAbsolutePosition();
  20487. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20488. if (!this._collider) {
  20489. this._collider = new BABYLON.Collider();
  20490. }
  20491. this._collider._radius = this.ellipsoid;
  20492. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20493. return this;
  20494. };
  20495. // Submeshes octree
  20496. /**
  20497. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20498. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20499. * @param maxCapacity defines the maximum size of each block (64 by default)
  20500. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20501. * @returns the new octree
  20502. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20503. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20504. */
  20505. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20506. if (maxCapacity === void 0) { maxCapacity = 64; }
  20507. if (maxDepth === void 0) { maxDepth = 2; }
  20508. if (!this._submeshesOctree) {
  20509. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20510. }
  20511. this.computeWorldMatrix(true);
  20512. var boundingInfo = this.getBoundingInfo();
  20513. // Update octree
  20514. var bbox = boundingInfo.boundingBox;
  20515. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20516. return this._submeshesOctree;
  20517. };
  20518. // Collisions
  20519. /** @hidden */
  20520. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20521. this._generatePointsArray();
  20522. if (!this._positions) {
  20523. return this;
  20524. }
  20525. // Transformation
  20526. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20527. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20528. subMesh._lastColliderWorldVertices = [];
  20529. subMesh._trianglePlanes = [];
  20530. var start = subMesh.verticesStart;
  20531. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20532. for (var i = start; i < end; i++) {
  20533. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20534. }
  20535. }
  20536. // Collide
  20537. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20538. if (collider.collisionFound) {
  20539. collider.collidedMesh = this;
  20540. }
  20541. return this;
  20542. };
  20543. /** @hidden */
  20544. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20545. var subMeshes;
  20546. var len;
  20547. // Octrees
  20548. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20549. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20550. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20551. len = intersections.length;
  20552. subMeshes = intersections.data;
  20553. }
  20554. else {
  20555. subMeshes = this.subMeshes;
  20556. len = subMeshes.length;
  20557. }
  20558. for (var index = 0; index < len; index++) {
  20559. var subMesh = subMeshes[index];
  20560. // Bounding test
  20561. if (len > 1 && !subMesh._checkCollision(collider))
  20562. continue;
  20563. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20564. }
  20565. return this;
  20566. };
  20567. /** @hidden */
  20568. AbstractMesh.prototype._checkCollision = function (collider) {
  20569. // Bounding box test
  20570. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20571. return this;
  20572. // Transformation matrix
  20573. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20574. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20575. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20576. return this;
  20577. };
  20578. // Picking
  20579. /** @hidden */
  20580. AbstractMesh.prototype._generatePointsArray = function () {
  20581. return false;
  20582. };
  20583. /**
  20584. * Checks if the passed Ray intersects with the mesh
  20585. * @param ray defines the ray to use
  20586. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20587. * @returns the picking info
  20588. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20589. */
  20590. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20591. var pickingInfo = new BABYLON.PickingInfo();
  20592. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20593. return pickingInfo;
  20594. }
  20595. if (!this._generatePointsArray()) {
  20596. return pickingInfo;
  20597. }
  20598. var intersectInfo = null;
  20599. // Octrees
  20600. var subMeshes;
  20601. var len;
  20602. if (this._submeshesOctree && this.useOctreeForPicking) {
  20603. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20604. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20605. len = intersections.length;
  20606. subMeshes = intersections.data;
  20607. }
  20608. else {
  20609. subMeshes = this.subMeshes;
  20610. len = subMeshes.length;
  20611. }
  20612. for (var index = 0; index < len; index++) {
  20613. var subMesh = subMeshes[index];
  20614. // Bounding test
  20615. if (len > 1 && !subMesh.canIntersects(ray))
  20616. continue;
  20617. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20618. if (currentIntersectInfo) {
  20619. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20620. intersectInfo = currentIntersectInfo;
  20621. intersectInfo.subMeshId = index;
  20622. if (fastCheck) {
  20623. break;
  20624. }
  20625. }
  20626. }
  20627. }
  20628. if (intersectInfo) {
  20629. // Get picked point
  20630. var world = this.getWorldMatrix();
  20631. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20632. var direction = ray.direction.clone();
  20633. direction = direction.scale(intersectInfo.distance);
  20634. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20635. var pickedPoint = worldOrigin.add(worldDirection);
  20636. // Return result
  20637. pickingInfo.hit = true;
  20638. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20639. pickingInfo.pickedPoint = pickedPoint;
  20640. pickingInfo.pickedMesh = this;
  20641. pickingInfo.bu = intersectInfo.bu || 0;
  20642. pickingInfo.bv = intersectInfo.bv || 0;
  20643. pickingInfo.faceId = intersectInfo.faceId;
  20644. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20645. return pickingInfo;
  20646. }
  20647. return pickingInfo;
  20648. };
  20649. /**
  20650. * Clones the current mesh
  20651. * @param name defines the mesh name
  20652. * @param newParent defines the new mesh parent
  20653. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20654. * @returns the new mesh
  20655. */
  20656. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20657. return null;
  20658. };
  20659. /**
  20660. * Disposes all the submeshes of the current meshnp
  20661. * @returns the current mesh
  20662. */
  20663. AbstractMesh.prototype.releaseSubMeshes = function () {
  20664. if (this.subMeshes) {
  20665. while (this.subMeshes.length) {
  20666. this.subMeshes[0].dispose();
  20667. }
  20668. }
  20669. else {
  20670. this.subMeshes = new Array();
  20671. }
  20672. return this;
  20673. };
  20674. /**
  20675. * Releases resources associated with this abstract mesh.
  20676. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20677. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20678. */
  20679. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20680. var _this = this;
  20681. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20682. var index;
  20683. // Smart Array Retainers.
  20684. this.getScene().freeActiveMeshes();
  20685. this.getScene().freeRenderingGroups();
  20686. // Action manager
  20687. if (this.actionManager !== undefined && this.actionManager !== null) {
  20688. this.actionManager.dispose();
  20689. this.actionManager = null;
  20690. }
  20691. // Skeleton
  20692. this._skeleton = null;
  20693. // Physics
  20694. if (this.physicsImpostor) {
  20695. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20696. }
  20697. // Intersections in progress
  20698. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20699. var other = this._intersectionsInProgress[index];
  20700. var pos = other._intersectionsInProgress.indexOf(this);
  20701. other._intersectionsInProgress.splice(pos, 1);
  20702. }
  20703. this._intersectionsInProgress = [];
  20704. // Lights
  20705. var lights = this.getScene().lights;
  20706. lights.forEach(function (light) {
  20707. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20708. if (meshIndex !== -1) {
  20709. light.includedOnlyMeshes.splice(meshIndex, 1);
  20710. }
  20711. meshIndex = light.excludedMeshes.indexOf(_this);
  20712. if (meshIndex !== -1) {
  20713. light.excludedMeshes.splice(meshIndex, 1);
  20714. }
  20715. // Shadow generators
  20716. var generator = light.getShadowGenerator();
  20717. if (generator) {
  20718. var shadowMap = generator.getShadowMap();
  20719. if (shadowMap && shadowMap.renderList) {
  20720. meshIndex = shadowMap.renderList.indexOf(_this);
  20721. if (meshIndex !== -1) {
  20722. shadowMap.renderList.splice(meshIndex, 1);
  20723. }
  20724. }
  20725. }
  20726. });
  20727. // Edges
  20728. if (this._edgesRenderer) {
  20729. this._edgesRenderer.dispose();
  20730. this._edgesRenderer = null;
  20731. }
  20732. // SubMeshes
  20733. if (this.getClassName() !== "InstancedMesh") {
  20734. this.releaseSubMeshes();
  20735. }
  20736. // Octree
  20737. var sceneOctree = this.getScene().selectionOctree;
  20738. if (sceneOctree !== undefined && sceneOctree !== null) {
  20739. var index = sceneOctree.dynamicContent.indexOf(this);
  20740. if (index !== -1) {
  20741. sceneOctree.dynamicContent.splice(index, 1);
  20742. }
  20743. }
  20744. // Query
  20745. var engine = this.getScene().getEngine();
  20746. if (this._occlusionQuery) {
  20747. this._isOcclusionQueryInProgress = false;
  20748. engine.deleteQuery(this._occlusionQuery);
  20749. this._occlusionQuery = null;
  20750. }
  20751. // Engine
  20752. engine.wipeCaches();
  20753. // Remove from scene
  20754. this.getScene().removeMesh(this);
  20755. if (disposeMaterialAndTextures) {
  20756. if (this.material) {
  20757. this.material.dispose(false, true);
  20758. }
  20759. }
  20760. if (!doNotRecurse) {
  20761. // Particles
  20762. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20763. if (this.getScene().particleSystems[index].emitter === this) {
  20764. this.getScene().particleSystems[index].dispose();
  20765. index--;
  20766. }
  20767. }
  20768. }
  20769. // facet data
  20770. if (this._facetDataEnabled) {
  20771. this.disableFacetData();
  20772. }
  20773. this.onAfterWorldMatrixUpdateObservable.clear();
  20774. this.onCollideObservable.clear();
  20775. this.onCollisionPositionChangeObservable.clear();
  20776. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20777. };
  20778. /**
  20779. * Adds the passed mesh as a child to the current mesh
  20780. * @param mesh defines the child mesh
  20781. * @returns the current mesh
  20782. */
  20783. AbstractMesh.prototype.addChild = function (mesh) {
  20784. mesh.setParent(this);
  20785. return this;
  20786. };
  20787. /**
  20788. * Removes the passed mesh from the current mesh children list
  20789. * @param mesh defines the child mesh
  20790. * @returns the current mesh
  20791. */
  20792. AbstractMesh.prototype.removeChild = function (mesh) {
  20793. mesh.setParent(null);
  20794. return this;
  20795. };
  20796. // Facet data
  20797. /** @hidden */
  20798. AbstractMesh.prototype._initFacetData = function () {
  20799. if (!this._facetNormals) {
  20800. this._facetNormals = new Array();
  20801. }
  20802. if (!this._facetPositions) {
  20803. this._facetPositions = new Array();
  20804. }
  20805. if (!this._facetPartitioning) {
  20806. this._facetPartitioning = new Array();
  20807. }
  20808. this._facetNb = (this.getIndices().length / 3) | 0;
  20809. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20810. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20811. for (var f = 0; f < this._facetNb; f++) {
  20812. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20813. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20814. }
  20815. this._facetDataEnabled = true;
  20816. return this;
  20817. };
  20818. /**
  20819. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20820. * This method can be called within the render loop.
  20821. * 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
  20822. * @returns the current mesh
  20823. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20824. */
  20825. AbstractMesh.prototype.updateFacetData = function () {
  20826. if (!this._facetDataEnabled) {
  20827. this._initFacetData();
  20828. }
  20829. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20830. var indices = this.getIndices();
  20831. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20832. var bInfo = this.getBoundingInfo();
  20833. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20834. // init arrays, matrix and sort function on first call
  20835. this._facetDepthSortEnabled = true;
  20836. if (indices instanceof Uint16Array) {
  20837. this._depthSortedIndices = new Uint16Array(indices);
  20838. }
  20839. else if (indices instanceof Uint32Array) {
  20840. this._depthSortedIndices = new Uint32Array(indices);
  20841. }
  20842. else {
  20843. var needs32bits = false;
  20844. for (var i = 0; i < indices.length; i++) {
  20845. if (indices[i] > 65535) {
  20846. needs32bits = true;
  20847. break;
  20848. }
  20849. }
  20850. if (needs32bits) {
  20851. this._depthSortedIndices = new Uint32Array(indices);
  20852. }
  20853. else {
  20854. this._depthSortedIndices = new Uint16Array(indices);
  20855. }
  20856. }
  20857. this._facetDepthSortFunction = function (f1, f2) {
  20858. return (f2.sqDistance - f1.sqDistance);
  20859. };
  20860. if (!this._facetDepthSortFrom) {
  20861. var camera = this.getScene().activeCamera;
  20862. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20863. }
  20864. this._depthSortedFacets = [];
  20865. for (var f = 0; f < this._facetNb; f++) {
  20866. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20867. this._depthSortedFacets.push(depthSortedFacet);
  20868. }
  20869. this._invertedMatrix = BABYLON.Matrix.Identity();
  20870. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20871. }
  20872. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20873. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20874. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20875. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20876. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20877. this._subDiv.max = this._partitioningSubdivisions;
  20878. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20879. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20880. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20881. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20882. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20883. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20884. // set the parameters for ComputeNormals()
  20885. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20886. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20887. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20888. this._facetParameters.bInfo = bInfo;
  20889. this._facetParameters.bbSize = this._bbSize;
  20890. this._facetParameters.subDiv = this._subDiv;
  20891. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20892. this._facetParameters.depthSort = this._facetDepthSort;
  20893. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20894. this.computeWorldMatrix(true);
  20895. this._worldMatrix.invertToRef(this._invertedMatrix);
  20896. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20897. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20898. }
  20899. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20900. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20901. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20902. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20903. var l = (this._depthSortedIndices.length / 3) | 0;
  20904. for (var f = 0; f < l; f++) {
  20905. var sind = this._depthSortedFacets[f].ind;
  20906. this._depthSortedIndices[f * 3] = indices[sind];
  20907. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20908. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20909. }
  20910. this.updateIndices(this._depthSortedIndices);
  20911. }
  20912. return this;
  20913. };
  20914. /**
  20915. * Returns the facetLocalNormals array.
  20916. * The normals are expressed in the mesh local spac
  20917. * @returns an array of Vector3
  20918. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20919. */
  20920. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20921. if (!this._facetNormals) {
  20922. this.updateFacetData();
  20923. }
  20924. return this._facetNormals;
  20925. };
  20926. /**
  20927. * Returns the facetLocalPositions array.
  20928. * The facet positions are expressed in the mesh local space
  20929. * @returns an array of Vector3
  20930. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20931. */
  20932. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20933. if (!this._facetPositions) {
  20934. this.updateFacetData();
  20935. }
  20936. return this._facetPositions;
  20937. };
  20938. /**
  20939. * Returns the facetLocalPartioning array
  20940. * @returns an array of array of numbers
  20941. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20942. */
  20943. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20944. if (!this._facetPartitioning) {
  20945. this.updateFacetData();
  20946. }
  20947. return this._facetPartitioning;
  20948. };
  20949. /**
  20950. * Returns the i-th facet position in the world system.
  20951. * This method allocates a new Vector3 per call
  20952. * @param i defines the facet index
  20953. * @returns a new Vector3
  20954. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20955. */
  20956. AbstractMesh.prototype.getFacetPosition = function (i) {
  20957. var pos = BABYLON.Vector3.Zero();
  20958. this.getFacetPositionToRef(i, pos);
  20959. return pos;
  20960. };
  20961. /**
  20962. * Sets the reference Vector3 with the i-th facet position in the world system
  20963. * @param i defines the facet index
  20964. * @param ref defines the target vector
  20965. * @returns the current mesh
  20966. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20967. */
  20968. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20969. var localPos = (this.getFacetLocalPositions())[i];
  20970. var world = this.getWorldMatrix();
  20971. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20972. return this;
  20973. };
  20974. /**
  20975. * Returns the i-th facet normal in the world system.
  20976. * This method allocates a new Vector3 per call
  20977. * @param i defines the facet index
  20978. * @returns a new Vector3
  20979. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20980. */
  20981. AbstractMesh.prototype.getFacetNormal = function (i) {
  20982. var norm = BABYLON.Vector3.Zero();
  20983. this.getFacetNormalToRef(i, norm);
  20984. return norm;
  20985. };
  20986. /**
  20987. * Sets the reference Vector3 with the i-th facet normal in the world system
  20988. * @param i defines the facet index
  20989. * @param ref defines the target vector
  20990. * @returns the current mesh
  20991. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20992. */
  20993. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20994. var localNorm = (this.getFacetLocalNormals())[i];
  20995. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20996. return this;
  20997. };
  20998. /**
  20999. * 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)
  21000. * @param x defines x coordinate
  21001. * @param y defines y coordinate
  21002. * @param z defines z coordinate
  21003. * @returns the array of facet indexes
  21004. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21005. */
  21006. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21007. var bInfo = this.getBoundingInfo();
  21008. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21009. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21010. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21011. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21012. return null;
  21013. }
  21014. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21015. };
  21016. /**
  21017. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21018. * @param projected sets as the (x,y,z) world projection on the facet
  21019. * @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
  21020. * @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
  21021. * @param x defines x coordinate
  21022. * @param y defines y coordinate
  21023. * @param z defines z coordinate
  21024. * @returns the face index if found (or null instead)
  21025. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21026. */
  21027. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21028. if (checkFace === void 0) { checkFace = false; }
  21029. if (facing === void 0) { facing = true; }
  21030. var world = this.getWorldMatrix();
  21031. var invMat = BABYLON.Tmp.Matrix[5];
  21032. world.invertToRef(invMat);
  21033. var invVect = BABYLON.Tmp.Vector3[8];
  21034. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21035. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21036. if (projected) {
  21037. // tranform the local computed projected vector to world coordinates
  21038. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21039. }
  21040. return closest;
  21041. };
  21042. /**
  21043. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21044. * @param projected sets as the (x,y,z) local projection on the facet
  21045. * @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
  21046. * @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
  21047. * @param x defines x coordinate
  21048. * @param y defines y coordinate
  21049. * @param z defines z coordinate
  21050. * @returns the face index if found (or null instead)
  21051. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21052. */
  21053. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21054. if (checkFace === void 0) { checkFace = false; }
  21055. if (facing === void 0) { facing = true; }
  21056. var closest = null;
  21057. var tmpx = 0.0;
  21058. var tmpy = 0.0;
  21059. var tmpz = 0.0;
  21060. var d = 0.0; // tmp dot facet normal * facet position
  21061. var t0 = 0.0;
  21062. var projx = 0.0;
  21063. var projy = 0.0;
  21064. var projz = 0.0;
  21065. // Get all the facets in the same partitioning block than (x, y, z)
  21066. var facetPositions = this.getFacetLocalPositions();
  21067. var facetNormals = this.getFacetLocalNormals();
  21068. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21069. if (!facetsInBlock) {
  21070. return null;
  21071. }
  21072. // Get the closest facet to (x, y, z)
  21073. var shortest = Number.MAX_VALUE; // init distance vars
  21074. var tmpDistance = shortest;
  21075. var fib; // current facet in the block
  21076. var norm; // current facet normal
  21077. var p0; // current facet barycenter position
  21078. // loop on all the facets in the current partitioning block
  21079. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21080. fib = facetsInBlock[idx];
  21081. norm = facetNormals[fib];
  21082. p0 = facetPositions[fib];
  21083. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21084. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21085. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21086. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21087. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21088. projx = x + norm.x * t0;
  21089. projy = y + norm.y * t0;
  21090. projz = z + norm.z * t0;
  21091. tmpx = projx - x;
  21092. tmpy = projy - y;
  21093. tmpz = projz - z;
  21094. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21095. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21096. shortest = tmpDistance;
  21097. closest = fib;
  21098. if (projected) {
  21099. projected.x = projx;
  21100. projected.y = projy;
  21101. projected.z = projz;
  21102. }
  21103. }
  21104. }
  21105. }
  21106. return closest;
  21107. };
  21108. /**
  21109. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21110. * @returns the parameters
  21111. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21112. */
  21113. AbstractMesh.prototype.getFacetDataParameters = function () {
  21114. return this._facetParameters;
  21115. };
  21116. /**
  21117. * Disables the feature FacetData and frees the related memory
  21118. * @returns the current mesh
  21119. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21120. */
  21121. AbstractMesh.prototype.disableFacetData = function () {
  21122. if (this._facetDataEnabled) {
  21123. this._facetDataEnabled = false;
  21124. this._facetPositions = new Array();
  21125. this._facetNormals = new Array();
  21126. this._facetPartitioning = new Array();
  21127. this._facetParameters = null;
  21128. this._depthSortedIndices = new Uint32Array(0);
  21129. }
  21130. return this;
  21131. };
  21132. /**
  21133. * Updates the AbstractMesh indices array
  21134. * @param indices defines the data source
  21135. * @returns the current mesh
  21136. */
  21137. AbstractMesh.prototype.updateIndices = function (indices) {
  21138. return this;
  21139. };
  21140. /**
  21141. * Creates new normals data for the mesh
  21142. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21143. * @returns the current mesh
  21144. */
  21145. AbstractMesh.prototype.createNormals = function (updatable) {
  21146. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21147. var indices = this.getIndices();
  21148. var normals;
  21149. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21150. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21151. }
  21152. else {
  21153. normals = [];
  21154. }
  21155. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21156. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21157. return this;
  21158. };
  21159. /**
  21160. * Align the mesh with a normal
  21161. * @param normal defines the normal to use
  21162. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21163. * @returns the current mesh
  21164. */
  21165. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21166. if (!upDirection) {
  21167. upDirection = BABYLON.Axis.Y;
  21168. }
  21169. var axisX = BABYLON.Tmp.Vector3[0];
  21170. var axisZ = BABYLON.Tmp.Vector3[1];
  21171. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21172. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21173. if (this.rotationQuaternion) {
  21174. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21175. }
  21176. else {
  21177. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21178. }
  21179. return this;
  21180. };
  21181. /** @hidden */
  21182. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21183. var engine = this.getEngine();
  21184. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21185. this._isOccluded = false;
  21186. return;
  21187. }
  21188. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21189. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21190. if (isOcclusionQueryAvailable) {
  21191. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21192. this._isOcclusionQueryInProgress = false;
  21193. this._occlusionInternalRetryCounter = 0;
  21194. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21195. }
  21196. else {
  21197. this._occlusionInternalRetryCounter++;
  21198. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21199. this._isOcclusionQueryInProgress = false;
  21200. this._occlusionInternalRetryCounter = 0;
  21201. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21202. // if strict continue the last state of the object.
  21203. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21204. }
  21205. else {
  21206. return;
  21207. }
  21208. }
  21209. }
  21210. var scene = this.getScene();
  21211. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21212. if (!this._occlusionQuery) {
  21213. this._occlusionQuery = engine.createQuery();
  21214. }
  21215. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21216. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21217. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21218. this._isOcclusionQueryInProgress = true;
  21219. };
  21220. /** No occlusion */
  21221. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21222. /** Occlusion set to optimisitic */
  21223. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21224. /** Occlusion set to strict */
  21225. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21226. /** Use an accurante occlusion algorithm */
  21227. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21228. /** Use a conservative occlusion algorithm */
  21229. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21230. return AbstractMesh;
  21231. }(BABYLON.TransformNode));
  21232. BABYLON.AbstractMesh = AbstractMesh;
  21233. })(BABYLON || (BABYLON = {}));
  21234. //# sourceMappingURL=babylon.abstractMesh.js.map
  21235. var BABYLON;
  21236. (function (BABYLON) {
  21237. /**
  21238. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21239. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21240. * 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.
  21241. */
  21242. var Light = /** @class */ (function (_super) {
  21243. __extends(Light, _super);
  21244. /**
  21245. * Creates a Light object in the scene.
  21246. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21247. * @param name The firendly name of the light
  21248. * @param scene The scene the light belongs too
  21249. */
  21250. function Light(name, scene) {
  21251. var _this = _super.call(this, name, scene) || this;
  21252. /**
  21253. * Diffuse gives the basic color to an object.
  21254. */
  21255. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21256. /**
  21257. * Specular produces a highlight color on an object.
  21258. * Note: This is note affecting PBR materials.
  21259. */
  21260. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21261. /**
  21262. * Strength of the light.
  21263. * Note: By default it is define in the framework own unit.
  21264. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21265. */
  21266. _this.intensity = 1.0;
  21267. /**
  21268. * Defines how far from the source the light is impacting in scene units.
  21269. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21270. */
  21271. _this.range = Number.MAX_VALUE;
  21272. /**
  21273. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21274. * of light.
  21275. */
  21276. _this._photometricScale = 1.0;
  21277. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21278. _this._radius = 0.00001;
  21279. /**
  21280. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21281. * exceeding the number allowed of the materials.
  21282. */
  21283. _this.renderPriority = 0;
  21284. /**
  21285. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21286. * the current shadow generator.
  21287. */
  21288. _this.shadowEnabled = true;
  21289. _this._excludeWithLayerMask = 0;
  21290. _this._includeOnlyWithLayerMask = 0;
  21291. _this._lightmapMode = 0;
  21292. /**
  21293. * @hidden Internal use only.
  21294. */
  21295. _this._excludedMeshesIds = new Array();
  21296. /**
  21297. * @hidden Internal use only.
  21298. */
  21299. _this._includedOnlyMeshesIds = new Array();
  21300. _this.getScene().addLight(_this);
  21301. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21302. _this._buildUniformLayout();
  21303. _this.includedOnlyMeshes = new Array();
  21304. _this.excludedMeshes = new Array();
  21305. _this._resyncMeshes();
  21306. return _this;
  21307. }
  21308. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21309. /**
  21310. * If every light affecting the material is in this lightmapMode,
  21311. * material.lightmapTexture adds or multiplies
  21312. * (depends on material.useLightmapAsShadowmap)
  21313. * after every other light calculations.
  21314. */
  21315. get: function () {
  21316. return Light._LIGHTMAP_DEFAULT;
  21317. },
  21318. enumerable: true,
  21319. configurable: true
  21320. });
  21321. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21322. /**
  21323. * material.lightmapTexture as only diffuse lighting from this light
  21324. * adds only specular lighting from this light
  21325. * adds dynamic shadows
  21326. */
  21327. get: function () {
  21328. return Light._LIGHTMAP_SPECULAR;
  21329. },
  21330. enumerable: true,
  21331. configurable: true
  21332. });
  21333. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21334. /**
  21335. * material.lightmapTexture as only lighting
  21336. * no light calculation from this light
  21337. * only adds dynamic shadows from this light
  21338. */
  21339. get: function () {
  21340. return Light._LIGHTMAP_SHADOWSONLY;
  21341. },
  21342. enumerable: true,
  21343. configurable: true
  21344. });
  21345. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21346. /**
  21347. * Each light type uses the default quantity according to its type:
  21348. * point/spot lights use luminous intensity
  21349. * directional lights use illuminance
  21350. */
  21351. get: function () {
  21352. return Light._INTENSITYMODE_AUTOMATIC;
  21353. },
  21354. enumerable: true,
  21355. configurable: true
  21356. });
  21357. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21358. /**
  21359. * lumen (lm)
  21360. */
  21361. get: function () {
  21362. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21363. },
  21364. enumerable: true,
  21365. configurable: true
  21366. });
  21367. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21368. /**
  21369. * candela (lm/sr)
  21370. */
  21371. get: function () {
  21372. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21373. },
  21374. enumerable: true,
  21375. configurable: true
  21376. });
  21377. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21378. /**
  21379. * lux (lm/m^2)
  21380. */
  21381. get: function () {
  21382. return Light._INTENSITYMODE_ILLUMINANCE;
  21383. },
  21384. enumerable: true,
  21385. configurable: true
  21386. });
  21387. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21388. /**
  21389. * nit (cd/m^2)
  21390. */
  21391. get: function () {
  21392. return Light._INTENSITYMODE_LUMINANCE;
  21393. },
  21394. enumerable: true,
  21395. configurable: true
  21396. });
  21397. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21398. /**
  21399. * Light type const id of the point light.
  21400. */
  21401. get: function () {
  21402. return Light._LIGHTTYPEID_POINTLIGHT;
  21403. },
  21404. enumerable: true,
  21405. configurable: true
  21406. });
  21407. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21408. /**
  21409. * Light type const id of the directional light.
  21410. */
  21411. get: function () {
  21412. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21413. },
  21414. enumerable: true,
  21415. configurable: true
  21416. });
  21417. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21418. /**
  21419. * Light type const id of the spot light.
  21420. */
  21421. get: function () {
  21422. return Light._LIGHTTYPEID_SPOTLIGHT;
  21423. },
  21424. enumerable: true,
  21425. configurable: true
  21426. });
  21427. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21428. /**
  21429. * Light type const id of the hemispheric light.
  21430. */
  21431. get: function () {
  21432. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21433. },
  21434. enumerable: true,
  21435. configurable: true
  21436. });
  21437. Object.defineProperty(Light.prototype, "intensityMode", {
  21438. /**
  21439. * Gets the photometric scale used to interpret the intensity.
  21440. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21441. */
  21442. get: function () {
  21443. return this._intensityMode;
  21444. },
  21445. /**
  21446. * Sets the photometric scale used to interpret the intensity.
  21447. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21448. */
  21449. set: function (value) {
  21450. this._intensityMode = value;
  21451. this._computePhotometricScale();
  21452. },
  21453. enumerable: true,
  21454. configurable: true
  21455. });
  21456. ;
  21457. ;
  21458. Object.defineProperty(Light.prototype, "radius", {
  21459. /**
  21460. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21461. */
  21462. get: function () {
  21463. return this._radius;
  21464. },
  21465. /**
  21466. * sets the light radius used by PBR Materials to simulate soft area lights.
  21467. */
  21468. set: function (value) {
  21469. this._radius = value;
  21470. this._computePhotometricScale();
  21471. },
  21472. enumerable: true,
  21473. configurable: true
  21474. });
  21475. ;
  21476. ;
  21477. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21478. /**
  21479. * Gets the only meshes impacted by this light.
  21480. */
  21481. get: function () {
  21482. return this._includedOnlyMeshes;
  21483. },
  21484. /**
  21485. * Sets the only meshes impacted by this light.
  21486. */
  21487. set: function (value) {
  21488. this._includedOnlyMeshes = value;
  21489. this._hookArrayForIncludedOnly(value);
  21490. },
  21491. enumerable: true,
  21492. configurable: true
  21493. });
  21494. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21495. /**
  21496. * Gets the meshes not impacted by this light.
  21497. */
  21498. get: function () {
  21499. return this._excludedMeshes;
  21500. },
  21501. /**
  21502. * Sets the meshes not impacted by this light.
  21503. */
  21504. set: function (value) {
  21505. this._excludedMeshes = value;
  21506. this._hookArrayForExcluded(value);
  21507. },
  21508. enumerable: true,
  21509. configurable: true
  21510. });
  21511. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21512. /**
  21513. * Gets the layer id use to find what meshes are not impacted by the light.
  21514. * Inactive if 0
  21515. */
  21516. get: function () {
  21517. return this._excludeWithLayerMask;
  21518. },
  21519. /**
  21520. * Sets the layer id use to find what meshes are not impacted by the light.
  21521. * Inactive if 0
  21522. */
  21523. set: function (value) {
  21524. this._excludeWithLayerMask = value;
  21525. this._resyncMeshes();
  21526. },
  21527. enumerable: true,
  21528. configurable: true
  21529. });
  21530. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21531. /**
  21532. * Gets the layer id use to find what meshes are impacted by the light.
  21533. * Inactive if 0
  21534. */
  21535. get: function () {
  21536. return this._includeOnlyWithLayerMask;
  21537. },
  21538. /**
  21539. * Sets the layer id use to find what meshes are impacted by the light.
  21540. * Inactive if 0
  21541. */
  21542. set: function (value) {
  21543. this._includeOnlyWithLayerMask = value;
  21544. this._resyncMeshes();
  21545. },
  21546. enumerable: true,
  21547. configurable: true
  21548. });
  21549. Object.defineProperty(Light.prototype, "lightmapMode", {
  21550. /**
  21551. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21552. */
  21553. get: function () {
  21554. return this._lightmapMode;
  21555. },
  21556. /**
  21557. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21558. */
  21559. set: function (value) {
  21560. if (this._lightmapMode === value) {
  21561. return;
  21562. }
  21563. this._lightmapMode = value;
  21564. this._markMeshesAsLightDirty();
  21565. },
  21566. enumerable: true,
  21567. configurable: true
  21568. });
  21569. /**
  21570. * Returns the string "Light".
  21571. * @returns the class name
  21572. */
  21573. Light.prototype.getClassName = function () {
  21574. return "Light";
  21575. };
  21576. /**
  21577. * Converts the light information to a readable string for debug purpose.
  21578. * @param fullDetails Supports for multiple levels of logging within scene loading
  21579. * @returns the human readable light info
  21580. */
  21581. Light.prototype.toString = function (fullDetails) {
  21582. var ret = "Name: " + this.name;
  21583. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21584. if (this.animations) {
  21585. for (var i = 0; i < this.animations.length; i++) {
  21586. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21587. }
  21588. }
  21589. if (fullDetails) {
  21590. }
  21591. return ret;
  21592. };
  21593. /**
  21594. * Set the enabled state of this node.
  21595. * @param value - the new enabled state
  21596. */
  21597. Light.prototype.setEnabled = function (value) {
  21598. _super.prototype.setEnabled.call(this, value);
  21599. this._resyncMeshes();
  21600. };
  21601. /**
  21602. * Returns the Light associated shadow generator if any.
  21603. * @return the associated shadow generator.
  21604. */
  21605. Light.prototype.getShadowGenerator = function () {
  21606. return this._shadowGenerator;
  21607. };
  21608. /**
  21609. * Returns a Vector3, the absolute light position in the World.
  21610. * @returns the world space position of the light
  21611. */
  21612. Light.prototype.getAbsolutePosition = function () {
  21613. return BABYLON.Vector3.Zero();
  21614. };
  21615. /**
  21616. * Specifies if the light will affect the passed mesh.
  21617. * @param mesh The mesh to test against the light
  21618. * @return true the mesh is affected otherwise, false.
  21619. */
  21620. Light.prototype.canAffectMesh = function (mesh) {
  21621. if (!mesh) {
  21622. return true;
  21623. }
  21624. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21625. return false;
  21626. }
  21627. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21628. return false;
  21629. }
  21630. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21631. return false;
  21632. }
  21633. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21634. return false;
  21635. }
  21636. return true;
  21637. };
  21638. /**
  21639. * Computes and Returns the light World matrix.
  21640. * @returns the world matrix
  21641. */
  21642. Light.prototype.getWorldMatrix = function () {
  21643. this._currentRenderId = this.getScene().getRenderId();
  21644. this._childRenderId = this._currentRenderId;
  21645. var worldMatrix = this._getWorldMatrix();
  21646. if (this.parent && this.parent.getWorldMatrix) {
  21647. if (!this._parentedWorldMatrix) {
  21648. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21649. }
  21650. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21651. this._markSyncedWithParent();
  21652. return this._parentedWorldMatrix;
  21653. }
  21654. return worldMatrix;
  21655. };
  21656. /**
  21657. * Sort function to order lights for rendering.
  21658. * @param a First Light object to compare to second.
  21659. * @param b Second Light object to compare first.
  21660. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21661. */
  21662. Light.CompareLightsPriority = function (a, b) {
  21663. //shadow-casting lights have priority over non-shadow-casting lights
  21664. //the renderPrioirty is a secondary sort criterion
  21665. if (a.shadowEnabled !== b.shadowEnabled) {
  21666. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21667. }
  21668. return b.renderPriority - a.renderPriority;
  21669. };
  21670. /**
  21671. * Releases resources associated with this node.
  21672. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21673. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21674. */
  21675. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21676. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21677. if (this._shadowGenerator) {
  21678. this._shadowGenerator.dispose();
  21679. this._shadowGenerator = null;
  21680. }
  21681. // Animations
  21682. this.getScene().stopAnimation(this);
  21683. // Remove from meshes
  21684. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21685. var mesh = _a[_i];
  21686. mesh._removeLightSource(this);
  21687. }
  21688. this._uniformBuffer.dispose();
  21689. // Remove from scene
  21690. this.getScene().removeLight(this);
  21691. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21692. };
  21693. /**
  21694. * Returns the light type ID (integer).
  21695. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21696. */
  21697. Light.prototype.getTypeID = function () {
  21698. return 0;
  21699. };
  21700. /**
  21701. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21702. * @returns the scaled intensity in intensity mode unit
  21703. */
  21704. Light.prototype.getScaledIntensity = function () {
  21705. return this._photometricScale * this.intensity;
  21706. };
  21707. /**
  21708. * Returns a new Light object, named "name", from the current one.
  21709. * @param name The name of the cloned light
  21710. * @returns the new created light
  21711. */
  21712. Light.prototype.clone = function (name) {
  21713. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21714. if (!constructor) {
  21715. return null;
  21716. }
  21717. return BABYLON.SerializationHelper.Clone(constructor, this);
  21718. };
  21719. /**
  21720. * Serializes the current light into a Serialization object.
  21721. * @returns the serialized object.
  21722. */
  21723. Light.prototype.serialize = function () {
  21724. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21725. // Type
  21726. serializationObject.type = this.getTypeID();
  21727. // Parent
  21728. if (this.parent) {
  21729. serializationObject.parentId = this.parent.id;
  21730. }
  21731. // Inclusion / exclusions
  21732. if (this.excludedMeshes.length > 0) {
  21733. serializationObject.excludedMeshesIds = [];
  21734. this.excludedMeshes.forEach(function (mesh) {
  21735. serializationObject.excludedMeshesIds.push(mesh.id);
  21736. });
  21737. }
  21738. if (this.includedOnlyMeshes.length > 0) {
  21739. serializationObject.includedOnlyMeshesIds = [];
  21740. this.includedOnlyMeshes.forEach(function (mesh) {
  21741. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21742. });
  21743. }
  21744. // Animations
  21745. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21746. serializationObject.ranges = this.serializeAnimationRanges();
  21747. return serializationObject;
  21748. };
  21749. /**
  21750. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21751. * This new light is named "name" and added to the passed scene.
  21752. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21753. * @param name The friendly name of the light
  21754. * @param scene The scene the new light will belong to
  21755. * @returns the constructor function
  21756. */
  21757. Light.GetConstructorFromName = function (type, name, scene) {
  21758. switch (type) {
  21759. case 0:
  21760. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21761. case 1:
  21762. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21763. case 2:
  21764. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21765. case 3:
  21766. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21767. }
  21768. return null;
  21769. };
  21770. /**
  21771. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21772. * @param parsedLight The JSON representation of the light
  21773. * @param scene The scene to create the parsed light in
  21774. * @returns the created light after parsing
  21775. */
  21776. Light.Parse = function (parsedLight, scene) {
  21777. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21778. if (!constructor) {
  21779. return null;
  21780. }
  21781. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21782. // Inclusion / exclusions
  21783. if (parsedLight.excludedMeshesIds) {
  21784. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21785. }
  21786. if (parsedLight.includedOnlyMeshesIds) {
  21787. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21788. }
  21789. // Parent
  21790. if (parsedLight.parentId) {
  21791. light._waitingParentId = parsedLight.parentId;
  21792. }
  21793. // Animations
  21794. if (parsedLight.animations) {
  21795. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21796. var parsedAnimation = parsedLight.animations[animationIndex];
  21797. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21798. }
  21799. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21800. }
  21801. if (parsedLight.autoAnimate) {
  21802. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21803. }
  21804. return light;
  21805. };
  21806. Light.prototype._hookArrayForExcluded = function (array) {
  21807. var _this = this;
  21808. var oldPush = array.push;
  21809. array.push = function () {
  21810. var items = [];
  21811. for (var _i = 0; _i < arguments.length; _i++) {
  21812. items[_i] = arguments[_i];
  21813. }
  21814. var result = oldPush.apply(array, items);
  21815. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21816. var item = items_1[_a];
  21817. item._resyncLighSource(_this);
  21818. }
  21819. return result;
  21820. };
  21821. var oldSplice = array.splice;
  21822. array.splice = function (index, deleteCount) {
  21823. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21824. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21825. var item = deleted_1[_i];
  21826. item._resyncLighSource(_this);
  21827. }
  21828. return deleted;
  21829. };
  21830. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21831. var item = array_1[_i];
  21832. item._resyncLighSource(this);
  21833. }
  21834. };
  21835. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21836. var _this = this;
  21837. var oldPush = array.push;
  21838. array.push = function () {
  21839. var items = [];
  21840. for (var _i = 0; _i < arguments.length; _i++) {
  21841. items[_i] = arguments[_i];
  21842. }
  21843. var result = oldPush.apply(array, items);
  21844. _this._resyncMeshes();
  21845. return result;
  21846. };
  21847. var oldSplice = array.splice;
  21848. array.splice = function (index, deleteCount) {
  21849. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21850. _this._resyncMeshes();
  21851. return deleted;
  21852. };
  21853. this._resyncMeshes();
  21854. };
  21855. Light.prototype._resyncMeshes = function () {
  21856. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21857. var mesh = _a[_i];
  21858. mesh._resyncLighSource(this);
  21859. }
  21860. };
  21861. /**
  21862. * Forces the meshes to update their light related information in their rendering used effects
  21863. * @hidden Internal Use Only
  21864. */
  21865. Light.prototype._markMeshesAsLightDirty = function () {
  21866. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21867. var mesh = _a[_i];
  21868. if (mesh._lightSources.indexOf(this) !== -1) {
  21869. mesh._markSubMeshesAsLightDirty();
  21870. }
  21871. }
  21872. };
  21873. /**
  21874. * Recomputes the cached photometric scale if needed.
  21875. */
  21876. Light.prototype._computePhotometricScale = function () {
  21877. this._photometricScale = this._getPhotometricScale();
  21878. this.getScene().resetCachedMaterial();
  21879. };
  21880. /**
  21881. * Returns the Photometric Scale according to the light type and intensity mode.
  21882. */
  21883. Light.prototype._getPhotometricScale = function () {
  21884. var photometricScale = 0.0;
  21885. var lightTypeID = this.getTypeID();
  21886. //get photometric mode
  21887. var photometricMode = this.intensityMode;
  21888. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21889. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21890. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21891. }
  21892. else {
  21893. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21894. }
  21895. }
  21896. //compute photometric scale
  21897. switch (lightTypeID) {
  21898. case Light.LIGHTTYPEID_POINTLIGHT:
  21899. case Light.LIGHTTYPEID_SPOTLIGHT:
  21900. switch (photometricMode) {
  21901. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21902. photometricScale = 1.0 / (4.0 * Math.PI);
  21903. break;
  21904. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21905. photometricScale = 1.0;
  21906. break;
  21907. case Light.INTENSITYMODE_LUMINANCE:
  21908. photometricScale = this.radius * this.radius;
  21909. break;
  21910. }
  21911. break;
  21912. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21913. switch (photometricMode) {
  21914. case Light.INTENSITYMODE_ILLUMINANCE:
  21915. photometricScale = 1.0;
  21916. break;
  21917. case Light.INTENSITYMODE_LUMINANCE:
  21918. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21919. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21920. var apexAngleRadians = this.radius;
  21921. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21922. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21923. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21924. photometricScale = solidAngle;
  21925. break;
  21926. }
  21927. break;
  21928. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21929. // No fall off in hemisperic light.
  21930. photometricScale = 1.0;
  21931. break;
  21932. }
  21933. return photometricScale;
  21934. };
  21935. /**
  21936. * Reorder the light in the scene according to their defined priority.
  21937. * @hidden Internal Use Only
  21938. */
  21939. Light.prototype._reorderLightsInScene = function () {
  21940. var scene = this.getScene();
  21941. if (this._renderPriority != 0) {
  21942. scene.requireLightSorting = true;
  21943. }
  21944. this.getScene().sortLightsByPriority();
  21945. };
  21946. //lightmapMode Consts
  21947. Light._LIGHTMAP_DEFAULT = 0;
  21948. Light._LIGHTMAP_SPECULAR = 1;
  21949. Light._LIGHTMAP_SHADOWSONLY = 2;
  21950. // Intensity Mode Consts
  21951. Light._INTENSITYMODE_AUTOMATIC = 0;
  21952. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21953. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21954. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21955. Light._INTENSITYMODE_LUMINANCE = 4;
  21956. // Light types ids const.
  21957. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21958. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21959. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21960. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21961. __decorate([
  21962. BABYLON.serializeAsColor3()
  21963. ], Light.prototype, "diffuse", void 0);
  21964. __decorate([
  21965. BABYLON.serializeAsColor3()
  21966. ], Light.prototype, "specular", void 0);
  21967. __decorate([
  21968. BABYLON.serialize()
  21969. ], Light.prototype, "intensity", void 0);
  21970. __decorate([
  21971. BABYLON.serialize()
  21972. ], Light.prototype, "range", void 0);
  21973. __decorate([
  21974. BABYLON.serialize()
  21975. ], Light.prototype, "intensityMode", null);
  21976. __decorate([
  21977. BABYLON.serialize()
  21978. ], Light.prototype, "radius", null);
  21979. __decorate([
  21980. BABYLON.serialize()
  21981. ], Light.prototype, "_renderPriority", void 0);
  21982. __decorate([
  21983. BABYLON.expandToProperty("_reorderLightsInScene")
  21984. ], Light.prototype, "renderPriority", void 0);
  21985. __decorate([
  21986. BABYLON.serialize()
  21987. ], Light.prototype, "shadowEnabled", void 0);
  21988. __decorate([
  21989. BABYLON.serialize("excludeWithLayerMask")
  21990. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21991. __decorate([
  21992. BABYLON.serialize("includeOnlyWithLayerMask")
  21993. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21994. __decorate([
  21995. BABYLON.serialize("lightmapMode")
  21996. ], Light.prototype, "_lightmapMode", void 0);
  21997. return Light;
  21998. }(BABYLON.Node));
  21999. BABYLON.Light = Light;
  22000. })(BABYLON || (BABYLON = {}));
  22001. //# sourceMappingURL=babylon.light.js.map
  22002. var BABYLON;
  22003. (function (BABYLON) {
  22004. var Camera = /** @class */ (function (_super) {
  22005. __extends(Camera, _super);
  22006. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22007. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22008. var _this = _super.call(this, name, scene) || this;
  22009. /**
  22010. * The vector the camera should consider as up.
  22011. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22012. */
  22013. _this.upVector = BABYLON.Vector3.Up();
  22014. _this.orthoLeft = null;
  22015. _this.orthoRight = null;
  22016. _this.orthoBottom = null;
  22017. _this.orthoTop = null;
  22018. /**
  22019. * FOV is set in Radians. (default is 0.8)
  22020. */
  22021. _this.fov = 0.8;
  22022. _this.minZ = 1;
  22023. _this.maxZ = 10000.0;
  22024. _this.inertia = 0.9;
  22025. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22026. _this.isIntermediate = false;
  22027. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22028. /**
  22029. * Restricts the camera to viewing objects with the same layerMask.
  22030. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22031. */
  22032. _this.layerMask = 0x0FFFFFFF;
  22033. /**
  22034. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22035. */
  22036. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22037. // Camera rig members
  22038. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22039. _this._rigCameras = new Array();
  22040. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22041. _this._skipRendering = false;
  22042. _this.customRenderTargets = new Array();
  22043. // Observables
  22044. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22045. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22046. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22047. _this.onRestoreStateObservable = new BABYLON.Observable();
  22048. // Cache
  22049. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22050. _this._projectionMatrix = new BABYLON.Matrix();
  22051. _this._doNotComputeProjectionMatrix = false;
  22052. _this._worldMatrix = BABYLON.Matrix.Identity();
  22053. _this._postProcesses = new Array();
  22054. _this._transformMatrix = BABYLON.Matrix.Zero();
  22055. _this._activeMeshes = new BABYLON.SmartArray(256);
  22056. _this._globalPosition = BABYLON.Vector3.Zero();
  22057. _this._refreshFrustumPlanes = true;
  22058. _this.getScene().addCamera(_this);
  22059. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22060. _this.getScene().activeCamera = _this;
  22061. }
  22062. _this.position = position;
  22063. return _this;
  22064. }
  22065. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22066. get: function () {
  22067. return Camera._PERSPECTIVE_CAMERA;
  22068. },
  22069. enumerable: true,
  22070. configurable: true
  22071. });
  22072. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22073. get: function () {
  22074. return Camera._ORTHOGRAPHIC_CAMERA;
  22075. },
  22076. enumerable: true,
  22077. configurable: true
  22078. });
  22079. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22080. /**
  22081. * This is the default FOV mode for perspective cameras.
  22082. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22083. *
  22084. */
  22085. get: function () {
  22086. return Camera._FOVMODE_VERTICAL_FIXED;
  22087. },
  22088. enumerable: true,
  22089. configurable: true
  22090. });
  22091. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22092. /**
  22093. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22094. *
  22095. */
  22096. get: function () {
  22097. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22098. },
  22099. enumerable: true,
  22100. configurable: true
  22101. });
  22102. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22103. get: function () {
  22104. return Camera._RIG_MODE_NONE;
  22105. },
  22106. enumerable: true,
  22107. configurable: true
  22108. });
  22109. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22110. get: function () {
  22111. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22112. },
  22113. enumerable: true,
  22114. configurable: true
  22115. });
  22116. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22117. get: function () {
  22118. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22119. },
  22120. enumerable: true,
  22121. configurable: true
  22122. });
  22123. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22124. get: function () {
  22125. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22126. },
  22127. enumerable: true,
  22128. configurable: true
  22129. });
  22130. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22131. get: function () {
  22132. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22133. },
  22134. enumerable: true,
  22135. configurable: true
  22136. });
  22137. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22138. get: function () {
  22139. return Camera._RIG_MODE_VR;
  22140. },
  22141. enumerable: true,
  22142. configurable: true
  22143. });
  22144. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22145. get: function () {
  22146. return Camera._RIG_MODE_WEBVR;
  22147. },
  22148. enumerable: true,
  22149. configurable: true
  22150. });
  22151. /**
  22152. * Store current camera state (fov, position, etc..)
  22153. */
  22154. Camera.prototype.storeState = function () {
  22155. this._stateStored = true;
  22156. this._storedFov = this.fov;
  22157. return this;
  22158. };
  22159. /**
  22160. * Restores the camera state values if it has been stored. You must call storeState() first
  22161. */
  22162. Camera.prototype._restoreStateValues = function () {
  22163. if (!this._stateStored) {
  22164. return false;
  22165. }
  22166. this.fov = this._storedFov;
  22167. return true;
  22168. };
  22169. /**
  22170. * Restored camera state. You must call storeState() first
  22171. */
  22172. Camera.prototype.restoreState = function () {
  22173. if (this._restoreStateValues()) {
  22174. this.onRestoreStateObservable.notifyObservers(this);
  22175. return true;
  22176. }
  22177. return false;
  22178. };
  22179. Camera.prototype.getClassName = function () {
  22180. return "Camera";
  22181. };
  22182. /**
  22183. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22184. */
  22185. Camera.prototype.toString = function (fullDetails) {
  22186. var ret = "Name: " + this.name;
  22187. ret += ", type: " + this.getClassName();
  22188. if (this.animations) {
  22189. for (var i = 0; i < this.animations.length; i++) {
  22190. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22191. }
  22192. }
  22193. if (fullDetails) {
  22194. }
  22195. return ret;
  22196. };
  22197. Object.defineProperty(Camera.prototype, "globalPosition", {
  22198. get: function () {
  22199. return this._globalPosition;
  22200. },
  22201. enumerable: true,
  22202. configurable: true
  22203. });
  22204. Camera.prototype.getActiveMeshes = function () {
  22205. return this._activeMeshes;
  22206. };
  22207. Camera.prototype.isActiveMesh = function (mesh) {
  22208. return (this._activeMeshes.indexOf(mesh) !== -1);
  22209. };
  22210. /**
  22211. * Is this camera ready to be used/rendered
  22212. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22213. * @return true if the camera is ready
  22214. */
  22215. Camera.prototype.isReady = function (completeCheck) {
  22216. if (completeCheck === void 0) { completeCheck = false; }
  22217. if (completeCheck) {
  22218. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22219. var pp = _a[_i];
  22220. if (pp && !pp.isReady()) {
  22221. return false;
  22222. }
  22223. }
  22224. }
  22225. return _super.prototype.isReady.call(this, completeCheck);
  22226. };
  22227. //Cache
  22228. Camera.prototype._initCache = function () {
  22229. _super.prototype._initCache.call(this);
  22230. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22231. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22232. this._cache.mode = undefined;
  22233. this._cache.minZ = undefined;
  22234. this._cache.maxZ = undefined;
  22235. this._cache.fov = undefined;
  22236. this._cache.fovMode = undefined;
  22237. this._cache.aspectRatio = undefined;
  22238. this._cache.orthoLeft = undefined;
  22239. this._cache.orthoRight = undefined;
  22240. this._cache.orthoBottom = undefined;
  22241. this._cache.orthoTop = undefined;
  22242. this._cache.renderWidth = undefined;
  22243. this._cache.renderHeight = undefined;
  22244. };
  22245. Camera.prototype._updateCache = function (ignoreParentClass) {
  22246. if (!ignoreParentClass) {
  22247. _super.prototype._updateCache.call(this);
  22248. }
  22249. this._cache.position.copyFrom(this.position);
  22250. this._cache.upVector.copyFrom(this.upVector);
  22251. };
  22252. // Synchronized
  22253. Camera.prototype._isSynchronized = function () {
  22254. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22255. };
  22256. Camera.prototype._isSynchronizedViewMatrix = function () {
  22257. if (!_super.prototype._isSynchronized.call(this))
  22258. return false;
  22259. return this._cache.position.equals(this.position)
  22260. && this._cache.upVector.equals(this.upVector)
  22261. && this.isSynchronizedWithParent();
  22262. };
  22263. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22264. var check = this._cache.mode === this.mode
  22265. && this._cache.minZ === this.minZ
  22266. && this._cache.maxZ === this.maxZ;
  22267. if (!check) {
  22268. return false;
  22269. }
  22270. var engine = this.getEngine();
  22271. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22272. check = this._cache.fov === this.fov
  22273. && this._cache.fovMode === this.fovMode
  22274. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22275. }
  22276. else {
  22277. check = this._cache.orthoLeft === this.orthoLeft
  22278. && this._cache.orthoRight === this.orthoRight
  22279. && this._cache.orthoBottom === this.orthoBottom
  22280. && this._cache.orthoTop === this.orthoTop
  22281. && this._cache.renderWidth === engine.getRenderWidth()
  22282. && this._cache.renderHeight === engine.getRenderHeight();
  22283. }
  22284. return check;
  22285. };
  22286. // Controls
  22287. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22288. };
  22289. Camera.prototype.detachControl = function (element) {
  22290. };
  22291. Camera.prototype.update = function () {
  22292. this._checkInputs();
  22293. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22294. this._updateRigCameras();
  22295. }
  22296. };
  22297. Camera.prototype._checkInputs = function () {
  22298. this.onAfterCheckInputsObservable.notifyObservers(this);
  22299. };
  22300. Object.defineProperty(Camera.prototype, "rigCameras", {
  22301. get: function () {
  22302. return this._rigCameras;
  22303. },
  22304. enumerable: true,
  22305. configurable: true
  22306. });
  22307. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22308. get: function () {
  22309. return this._rigPostProcess;
  22310. },
  22311. enumerable: true,
  22312. configurable: true
  22313. });
  22314. /**
  22315. * Internal, gets the first post proces.
  22316. * @returns the first post process to be run on this camera.
  22317. */
  22318. Camera.prototype._getFirstPostProcess = function () {
  22319. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22320. if (this._postProcesses[ppIndex] !== null) {
  22321. return this._postProcesses[ppIndex];
  22322. }
  22323. }
  22324. return null;
  22325. };
  22326. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22327. // invalidate framebuffer
  22328. var firstPostProcess = this._getFirstPostProcess();
  22329. if (firstPostProcess) {
  22330. firstPostProcess.markTextureDirty();
  22331. }
  22332. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22333. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22334. var cam = this._rigCameras[i];
  22335. var rigPostProcess = cam._rigPostProcess;
  22336. // for VR rig, there does not have to be a post process
  22337. if (rigPostProcess) {
  22338. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22339. if (isPass) {
  22340. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22341. cam.isIntermediate = this._postProcesses.length === 0;
  22342. }
  22343. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22344. rigPostProcess.markTextureDirty();
  22345. }
  22346. else {
  22347. cam._postProcesses = this._postProcesses.slice(0);
  22348. }
  22349. }
  22350. };
  22351. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22352. if (insertAt === void 0) { insertAt = null; }
  22353. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22354. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22355. return 0;
  22356. }
  22357. if (insertAt == null || insertAt < 0) {
  22358. this._postProcesses.push(postProcess);
  22359. }
  22360. else if (this._postProcesses[insertAt] === null) {
  22361. this._postProcesses[insertAt] = postProcess;
  22362. }
  22363. else {
  22364. this._postProcesses.splice(insertAt, 0, postProcess);
  22365. }
  22366. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22367. return this._postProcesses.indexOf(postProcess);
  22368. };
  22369. Camera.prototype.detachPostProcess = function (postProcess) {
  22370. var idx = this._postProcesses.indexOf(postProcess);
  22371. if (idx !== -1) {
  22372. this._postProcesses[idx] = null;
  22373. }
  22374. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22375. };
  22376. Camera.prototype.getWorldMatrix = function () {
  22377. if (this._isSynchronizedViewMatrix()) {
  22378. return this._worldMatrix;
  22379. }
  22380. // Getting the the view matrix will also compute the world matrix.
  22381. this.getViewMatrix();
  22382. return this._worldMatrix;
  22383. };
  22384. Camera.prototype._getViewMatrix = function () {
  22385. return BABYLON.Matrix.Identity();
  22386. };
  22387. Camera.prototype.getViewMatrix = function (force) {
  22388. if (!force && this._isSynchronizedViewMatrix()) {
  22389. return this._computedViewMatrix;
  22390. }
  22391. this.updateCache();
  22392. this._computedViewMatrix = this._getViewMatrix();
  22393. this._currentRenderId = this.getScene().getRenderId();
  22394. this._childRenderId = this._currentRenderId;
  22395. this._refreshFrustumPlanes = true;
  22396. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22397. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22398. }
  22399. this.onViewMatrixChangedObservable.notifyObservers(this);
  22400. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22401. return this._computedViewMatrix;
  22402. };
  22403. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22404. this._doNotComputeProjectionMatrix = true;
  22405. if (projection !== undefined) {
  22406. this._projectionMatrix = projection;
  22407. }
  22408. };
  22409. ;
  22410. Camera.prototype.unfreezeProjectionMatrix = function () {
  22411. this._doNotComputeProjectionMatrix = false;
  22412. };
  22413. ;
  22414. Camera.prototype.getProjectionMatrix = function (force) {
  22415. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22416. return this._projectionMatrix;
  22417. }
  22418. // Cache
  22419. this._cache.mode = this.mode;
  22420. this._cache.minZ = this.minZ;
  22421. this._cache.maxZ = this.maxZ;
  22422. // Matrix
  22423. this._refreshFrustumPlanes = true;
  22424. var engine = this.getEngine();
  22425. var scene = this.getScene();
  22426. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22427. this._cache.fov = this.fov;
  22428. this._cache.fovMode = this.fovMode;
  22429. this._cache.aspectRatio = engine.getAspectRatio(this);
  22430. if (this.minZ <= 0) {
  22431. this.minZ = 0.1;
  22432. }
  22433. if (scene.useRightHandedSystem) {
  22434. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22435. }
  22436. else {
  22437. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22438. }
  22439. }
  22440. else {
  22441. var halfWidth = engine.getRenderWidth() / 2.0;
  22442. var halfHeight = engine.getRenderHeight() / 2.0;
  22443. if (scene.useRightHandedSystem) {
  22444. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22445. }
  22446. else {
  22447. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22448. }
  22449. this._cache.orthoLeft = this.orthoLeft;
  22450. this._cache.orthoRight = this.orthoRight;
  22451. this._cache.orthoBottom = this.orthoBottom;
  22452. this._cache.orthoTop = this.orthoTop;
  22453. this._cache.renderWidth = engine.getRenderWidth();
  22454. this._cache.renderHeight = engine.getRenderHeight();
  22455. }
  22456. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22457. return this._projectionMatrix;
  22458. };
  22459. Camera.prototype.getTranformationMatrix = function () {
  22460. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22461. return this._transformMatrix;
  22462. };
  22463. Camera.prototype.updateFrustumPlanes = function () {
  22464. if (!this._refreshFrustumPlanes) {
  22465. return;
  22466. }
  22467. this.getTranformationMatrix();
  22468. if (!this._frustumPlanes) {
  22469. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22470. }
  22471. else {
  22472. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22473. }
  22474. this._refreshFrustumPlanes = false;
  22475. };
  22476. Camera.prototype.isInFrustum = function (target) {
  22477. this.updateFrustumPlanes();
  22478. return target.isInFrustum(this._frustumPlanes);
  22479. };
  22480. Camera.prototype.isCompletelyInFrustum = function (target) {
  22481. this.updateFrustumPlanes();
  22482. return target.isCompletelyInFrustum(this._frustumPlanes);
  22483. };
  22484. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22485. if (length === void 0) { length = 100; }
  22486. if (!transform) {
  22487. transform = this.getWorldMatrix();
  22488. }
  22489. if (!origin) {
  22490. origin = this.position;
  22491. }
  22492. var forward = new BABYLON.Vector3(0, 0, 1);
  22493. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22494. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22495. return new BABYLON.Ray(origin, direction, length);
  22496. };
  22497. /**
  22498. * Releases resources associated with this node.
  22499. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22500. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22501. */
  22502. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22503. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22504. // Observables
  22505. this.onViewMatrixChangedObservable.clear();
  22506. this.onProjectionMatrixChangedObservable.clear();
  22507. this.onAfterCheckInputsObservable.clear();
  22508. this.onRestoreStateObservable.clear();
  22509. // Inputs
  22510. if (this.inputs) {
  22511. this.inputs.clear();
  22512. }
  22513. // Animations
  22514. this.getScene().stopAnimation(this);
  22515. // Remove from scene
  22516. this.getScene().removeCamera(this);
  22517. while (this._rigCameras.length > 0) {
  22518. var camera = this._rigCameras.pop();
  22519. if (camera) {
  22520. camera.dispose();
  22521. }
  22522. }
  22523. // Postprocesses
  22524. if (this._rigPostProcess) {
  22525. this._rigPostProcess.dispose(this);
  22526. this._rigPostProcess = null;
  22527. this._postProcesses = [];
  22528. }
  22529. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22530. this._rigPostProcess = null;
  22531. this._postProcesses = [];
  22532. }
  22533. else {
  22534. var i = this._postProcesses.length;
  22535. while (--i >= 0) {
  22536. var postProcess = this._postProcesses[i];
  22537. if (postProcess) {
  22538. postProcess.dispose(this);
  22539. }
  22540. }
  22541. }
  22542. // Render targets
  22543. var i = this.customRenderTargets.length;
  22544. while (--i >= 0) {
  22545. this.customRenderTargets[i].dispose();
  22546. }
  22547. this.customRenderTargets = [];
  22548. // Active Meshes
  22549. this._activeMeshes.dispose();
  22550. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22551. };
  22552. Object.defineProperty(Camera.prototype, "leftCamera", {
  22553. // ---- Camera rigs section ----
  22554. get: function () {
  22555. if (this._rigCameras.length < 1) {
  22556. return null;
  22557. }
  22558. return this._rigCameras[0];
  22559. },
  22560. enumerable: true,
  22561. configurable: true
  22562. });
  22563. Object.defineProperty(Camera.prototype, "rightCamera", {
  22564. get: function () {
  22565. if (this._rigCameras.length < 2) {
  22566. return null;
  22567. }
  22568. return this._rigCameras[1];
  22569. },
  22570. enumerable: true,
  22571. configurable: true
  22572. });
  22573. Camera.prototype.getLeftTarget = function () {
  22574. if (this._rigCameras.length < 1) {
  22575. return null;
  22576. }
  22577. return this._rigCameras[0].getTarget();
  22578. };
  22579. Camera.prototype.getRightTarget = function () {
  22580. if (this._rigCameras.length < 2) {
  22581. return null;
  22582. }
  22583. return this._rigCameras[1].getTarget();
  22584. };
  22585. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22586. if (this.cameraRigMode === mode) {
  22587. return;
  22588. }
  22589. while (this._rigCameras.length > 0) {
  22590. var camera = this._rigCameras.pop();
  22591. if (camera) {
  22592. camera.dispose();
  22593. }
  22594. }
  22595. this.cameraRigMode = mode;
  22596. this._cameraRigParams = {};
  22597. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22598. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22599. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22600. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22601. // create the rig cameras, unless none
  22602. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22603. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22604. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22605. if (leftCamera && rightCamera) {
  22606. this._rigCameras.push(leftCamera);
  22607. this._rigCameras.push(rightCamera);
  22608. }
  22609. }
  22610. switch (this.cameraRigMode) {
  22611. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22612. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22613. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22614. break;
  22615. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22616. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22617. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22618. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22619. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22620. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22621. break;
  22622. case Camera.RIG_MODE_VR:
  22623. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22624. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22625. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22626. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22627. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22628. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22629. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22630. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22631. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22632. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22633. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22634. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22635. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22636. if (metrics.compensateDistortion) {
  22637. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22638. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22639. }
  22640. break;
  22641. case Camera.RIG_MODE_WEBVR:
  22642. if (rigParams.vrDisplay) {
  22643. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22644. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22645. //Left eye
  22646. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22647. this._rigCameras[0].setCameraRigParameter("left", true);
  22648. //leaving this for future reference
  22649. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22650. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22651. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22652. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22653. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22654. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22655. this._rigCameras[0].parent = this;
  22656. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22657. //Right eye
  22658. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22659. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22660. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22661. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22662. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22663. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22664. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22665. this._rigCameras[1].parent = this;
  22666. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22667. if (Camera.UseAlternateWebVRRendering) {
  22668. this._rigCameras[1]._skipRendering = true;
  22669. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22670. }
  22671. }
  22672. break;
  22673. }
  22674. this._cascadePostProcessesToRigCams();
  22675. this.update();
  22676. };
  22677. Camera.prototype._getVRProjectionMatrix = function () {
  22678. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22679. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22680. return this._projectionMatrix;
  22681. };
  22682. Camera.prototype._updateCameraRotationMatrix = function () {
  22683. //Here for WebVR
  22684. };
  22685. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22686. //Here for WebVR
  22687. };
  22688. /**
  22689. * This function MUST be overwritten by the different WebVR cameras available.
  22690. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22691. */
  22692. Camera.prototype._getWebVRProjectionMatrix = function () {
  22693. return BABYLON.Matrix.Identity();
  22694. };
  22695. /**
  22696. * This function MUST be overwritten by the different WebVR cameras available.
  22697. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22698. */
  22699. Camera.prototype._getWebVRViewMatrix = function () {
  22700. return BABYLON.Matrix.Identity();
  22701. };
  22702. Camera.prototype.setCameraRigParameter = function (name, value) {
  22703. if (!this._cameraRigParams) {
  22704. this._cameraRigParams = {};
  22705. }
  22706. this._cameraRigParams[name] = value;
  22707. //provisionnally:
  22708. if (name === "interaxialDistance") {
  22709. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22710. }
  22711. };
  22712. /**
  22713. * needs to be overridden by children so sub has required properties to be copied
  22714. */
  22715. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22716. return null;
  22717. };
  22718. /**
  22719. * May need to be overridden by children
  22720. */
  22721. Camera.prototype._updateRigCameras = function () {
  22722. for (var i = 0; i < this._rigCameras.length; i++) {
  22723. this._rigCameras[i].minZ = this.minZ;
  22724. this._rigCameras[i].maxZ = this.maxZ;
  22725. this._rigCameras[i].fov = this.fov;
  22726. }
  22727. // only update viewport when ANAGLYPH
  22728. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22729. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22730. }
  22731. };
  22732. Camera.prototype._setupInputs = function () {
  22733. };
  22734. Camera.prototype.serialize = function () {
  22735. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22736. // Type
  22737. serializationObject.type = this.getClassName();
  22738. // Parent
  22739. if (this.parent) {
  22740. serializationObject.parentId = this.parent.id;
  22741. }
  22742. if (this.inputs) {
  22743. this.inputs.serialize(serializationObject);
  22744. }
  22745. // Animations
  22746. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22747. serializationObject.ranges = this.serializeAnimationRanges();
  22748. return serializationObject;
  22749. };
  22750. Camera.prototype.clone = function (name) {
  22751. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22752. };
  22753. Camera.prototype.getDirection = function (localAxis) {
  22754. var result = BABYLON.Vector3.Zero();
  22755. this.getDirectionToRef(localAxis, result);
  22756. return result;
  22757. };
  22758. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22759. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22760. };
  22761. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22762. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22763. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22764. switch (type) {
  22765. case "ArcRotateCamera":
  22766. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22767. case "DeviceOrientationCamera":
  22768. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22769. case "FollowCamera":
  22770. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22771. case "ArcFollowCamera":
  22772. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22773. case "GamepadCamera":
  22774. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22775. case "TouchCamera":
  22776. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22777. case "VirtualJoysticksCamera":
  22778. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22779. case "WebVRFreeCamera":
  22780. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22781. case "WebVRGamepadCamera":
  22782. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22783. case "VRDeviceOrientationFreeCamera":
  22784. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22785. case "VRDeviceOrientationGamepadCamera":
  22786. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22787. case "AnaglyphArcRotateCamera":
  22788. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22789. case "AnaglyphFreeCamera":
  22790. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22791. case "AnaglyphGamepadCamera":
  22792. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22793. case "AnaglyphUniversalCamera":
  22794. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22795. case "StereoscopicArcRotateCamera":
  22796. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22797. case "StereoscopicFreeCamera":
  22798. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22799. case "StereoscopicGamepadCamera":
  22800. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22801. case "StereoscopicUniversalCamera":
  22802. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22803. case "FreeCamera": // Forcing Universal here
  22804. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22805. default: // Universal Camera is the default value
  22806. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22807. }
  22808. };
  22809. Camera.prototype.computeWorldMatrix = function () {
  22810. return this.getWorldMatrix();
  22811. };
  22812. Camera.Parse = function (parsedCamera, scene) {
  22813. var type = parsedCamera.type;
  22814. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22815. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22816. // Parent
  22817. if (parsedCamera.parentId) {
  22818. camera._waitingParentId = parsedCamera.parentId;
  22819. }
  22820. //If camera has an input manager, let it parse inputs settings
  22821. if (camera.inputs) {
  22822. camera.inputs.parse(parsedCamera);
  22823. camera._setupInputs();
  22824. }
  22825. if (camera.setPosition) { // need to force position
  22826. camera.position.copyFromFloats(0, 0, 0);
  22827. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22828. }
  22829. // Target
  22830. if (parsedCamera.target) {
  22831. if (camera.setTarget) {
  22832. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22833. }
  22834. }
  22835. // Apply 3d rig, when found
  22836. if (parsedCamera.cameraRigMode) {
  22837. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22838. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22839. }
  22840. // Animations
  22841. if (parsedCamera.animations) {
  22842. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22843. var parsedAnimation = parsedCamera.animations[animationIndex];
  22844. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22845. }
  22846. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22847. }
  22848. if (parsedCamera.autoAnimate) {
  22849. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22850. }
  22851. return camera;
  22852. };
  22853. // Statics
  22854. Camera._PERSPECTIVE_CAMERA = 0;
  22855. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22856. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22857. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22858. Camera._RIG_MODE_NONE = 0;
  22859. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22860. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22861. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22862. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22863. Camera._RIG_MODE_VR = 20;
  22864. Camera._RIG_MODE_WEBVR = 21;
  22865. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22866. Camera.UseAlternateWebVRRendering = false;
  22867. __decorate([
  22868. BABYLON.serializeAsVector3()
  22869. ], Camera.prototype, "position", void 0);
  22870. __decorate([
  22871. BABYLON.serializeAsVector3()
  22872. ], Camera.prototype, "upVector", void 0);
  22873. __decorate([
  22874. BABYLON.serialize()
  22875. ], Camera.prototype, "orthoLeft", void 0);
  22876. __decorate([
  22877. BABYLON.serialize()
  22878. ], Camera.prototype, "orthoRight", void 0);
  22879. __decorate([
  22880. BABYLON.serialize()
  22881. ], Camera.prototype, "orthoBottom", void 0);
  22882. __decorate([
  22883. BABYLON.serialize()
  22884. ], Camera.prototype, "orthoTop", void 0);
  22885. __decorate([
  22886. BABYLON.serialize()
  22887. ], Camera.prototype, "fov", void 0);
  22888. __decorate([
  22889. BABYLON.serialize()
  22890. ], Camera.prototype, "minZ", void 0);
  22891. __decorate([
  22892. BABYLON.serialize()
  22893. ], Camera.prototype, "maxZ", void 0);
  22894. __decorate([
  22895. BABYLON.serialize()
  22896. ], Camera.prototype, "inertia", void 0);
  22897. __decorate([
  22898. BABYLON.serialize()
  22899. ], Camera.prototype, "mode", void 0);
  22900. __decorate([
  22901. BABYLON.serialize()
  22902. ], Camera.prototype, "layerMask", void 0);
  22903. __decorate([
  22904. BABYLON.serialize()
  22905. ], Camera.prototype, "fovMode", void 0);
  22906. __decorate([
  22907. BABYLON.serialize()
  22908. ], Camera.prototype, "cameraRigMode", void 0);
  22909. __decorate([
  22910. BABYLON.serialize()
  22911. ], Camera.prototype, "interaxialDistance", void 0);
  22912. __decorate([
  22913. BABYLON.serialize()
  22914. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22915. return Camera;
  22916. }(BABYLON.Node));
  22917. BABYLON.Camera = Camera;
  22918. })(BABYLON || (BABYLON = {}));
  22919. //# sourceMappingURL=babylon.camera.js.map
  22920. var BABYLON;
  22921. (function (BABYLON) {
  22922. var RenderingManager = /** @class */ (function () {
  22923. function RenderingManager(scene) {
  22924. this._renderingGroups = new Array();
  22925. this._autoClearDepthStencil = {};
  22926. this._customOpaqueSortCompareFn = {};
  22927. this._customAlphaTestSortCompareFn = {};
  22928. this._customTransparentSortCompareFn = {};
  22929. this._renderinGroupInfo = null;
  22930. this._scene = scene;
  22931. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22932. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22933. }
  22934. }
  22935. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22936. if (depth === void 0) { depth = true; }
  22937. if (stencil === void 0) { stencil = true; }
  22938. if (this._depthStencilBufferAlreadyCleaned) {
  22939. return;
  22940. }
  22941. this._scene.getEngine().clear(null, false, depth, stencil);
  22942. this._depthStencilBufferAlreadyCleaned = true;
  22943. };
  22944. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22945. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22946. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22947. var info = null;
  22948. if (observable) {
  22949. if (!this._renderinGroupInfo) {
  22950. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22951. }
  22952. info = this._renderinGroupInfo;
  22953. info.scene = this._scene;
  22954. info.camera = this._scene.activeCamera;
  22955. }
  22956. // Dispatch sprites
  22957. if (renderSprites) {
  22958. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22959. var manager = this._scene.spriteManagers[index];
  22960. this.dispatchSprites(manager);
  22961. }
  22962. }
  22963. // Render
  22964. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22965. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22966. var renderingGroup = this._renderingGroups[index];
  22967. if (!renderingGroup && !observable)
  22968. continue;
  22969. var renderingGroupMask = 0;
  22970. // Fire PRECLEAR stage
  22971. if (observable && info) {
  22972. renderingGroupMask = Math.pow(2, index);
  22973. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22974. info.renderingGroupId = index;
  22975. observable.notifyObservers(info, renderingGroupMask);
  22976. }
  22977. // Clear depth/stencil if needed
  22978. if (RenderingManager.AUTOCLEAR) {
  22979. var autoClear = this._autoClearDepthStencil[index];
  22980. if (autoClear && autoClear.autoClear) {
  22981. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22982. }
  22983. }
  22984. if (observable && info) {
  22985. // Fire PREOPAQUE stage
  22986. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22987. observable.notifyObservers(info, renderingGroupMask);
  22988. // Fire PRETRANSPARENT stage
  22989. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22990. observable.notifyObservers(info, renderingGroupMask);
  22991. }
  22992. if (renderingGroup)
  22993. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22994. // Fire POSTTRANSPARENT stage
  22995. if (observable && info) {
  22996. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22997. observable.notifyObservers(info, renderingGroupMask);
  22998. }
  22999. }
  23000. };
  23001. RenderingManager.prototype.reset = function () {
  23002. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23003. var renderingGroup = this._renderingGroups[index];
  23004. if (renderingGroup) {
  23005. renderingGroup.prepare();
  23006. }
  23007. }
  23008. };
  23009. RenderingManager.prototype.dispose = function () {
  23010. this.freeRenderingGroups();
  23011. this._renderingGroups.length = 0;
  23012. };
  23013. /**
  23014. * Clear the info related to rendering groups preventing retention points during dispose.
  23015. */
  23016. RenderingManager.prototype.freeRenderingGroups = function () {
  23017. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23018. var renderingGroup = this._renderingGroups[index];
  23019. if (renderingGroup) {
  23020. renderingGroup.dispose();
  23021. }
  23022. }
  23023. };
  23024. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23025. if (this._renderingGroups[renderingGroupId] === undefined) {
  23026. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23027. }
  23028. };
  23029. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23030. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23031. this._prepareRenderingGroup(renderingGroupId);
  23032. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23033. };
  23034. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23035. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23036. this._prepareRenderingGroup(renderingGroupId);
  23037. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23038. };
  23039. /**
  23040. * @param subMesh The submesh to dispatch
  23041. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23042. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23043. */
  23044. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23045. if (mesh === undefined) {
  23046. mesh = subMesh.getMesh();
  23047. }
  23048. var renderingGroupId = mesh.renderingGroupId || 0;
  23049. this._prepareRenderingGroup(renderingGroupId);
  23050. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23051. };
  23052. /**
  23053. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23054. * This allowed control for front to back rendering or reversly depending of the special needs.
  23055. *
  23056. * @param renderingGroupId The rendering group id corresponding to its index
  23057. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23058. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23059. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23060. */
  23061. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23062. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23063. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23064. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23065. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23066. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23067. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23068. if (this._renderingGroups[renderingGroupId]) {
  23069. var group = this._renderingGroups[renderingGroupId];
  23070. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23071. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23072. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23073. }
  23074. };
  23075. /**
  23076. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23077. *
  23078. * @param renderingGroupId The rendering group id corresponding to its index
  23079. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23080. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23081. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23082. */
  23083. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23084. if (depth === void 0) { depth = true; }
  23085. if (stencil === void 0) { stencil = true; }
  23086. this._autoClearDepthStencil[renderingGroupId] = {
  23087. autoClear: autoClearDepthStencil,
  23088. depth: depth,
  23089. stencil: stencil
  23090. };
  23091. };
  23092. /**
  23093. * The max id used for rendering groups (not included)
  23094. */
  23095. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23096. /**
  23097. * The min id used for rendering groups (included)
  23098. */
  23099. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23100. /**
  23101. * Used to globally prevent autoclearing scenes.
  23102. */
  23103. RenderingManager.AUTOCLEAR = true;
  23104. return RenderingManager;
  23105. }());
  23106. BABYLON.RenderingManager = RenderingManager;
  23107. })(BABYLON || (BABYLON = {}));
  23108. //# sourceMappingURL=babylon.renderingManager.js.map
  23109. var BABYLON;
  23110. (function (BABYLON) {
  23111. var RenderingGroup = /** @class */ (function () {
  23112. /**
  23113. * Creates a new rendering group.
  23114. * @param index The rendering group index
  23115. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23116. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23117. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23118. */
  23119. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23120. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23121. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23122. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23123. this.index = index;
  23124. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23125. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23126. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23127. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23128. this._particleSystems = new BABYLON.SmartArray(256);
  23129. this._spriteManagers = new BABYLON.SmartArray(256);
  23130. this._edgesRenderers = new BABYLON.SmartArray(16);
  23131. this._scene = scene;
  23132. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23133. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23134. this.transparentSortCompareFn = transparentSortCompareFn;
  23135. }
  23136. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23137. /**
  23138. * Set the opaque sort comparison function.
  23139. * If null the sub meshes will be render in the order they were created
  23140. */
  23141. set: function (value) {
  23142. this._opaqueSortCompareFn = value;
  23143. if (value) {
  23144. this._renderOpaque = this.renderOpaqueSorted;
  23145. }
  23146. else {
  23147. this._renderOpaque = RenderingGroup.renderUnsorted;
  23148. }
  23149. },
  23150. enumerable: true,
  23151. configurable: true
  23152. });
  23153. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23154. /**
  23155. * Set the alpha test sort comparison function.
  23156. * If null the sub meshes will be render in the order they were created
  23157. */
  23158. set: function (value) {
  23159. this._alphaTestSortCompareFn = value;
  23160. if (value) {
  23161. this._renderAlphaTest = this.renderAlphaTestSorted;
  23162. }
  23163. else {
  23164. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23165. }
  23166. },
  23167. enumerable: true,
  23168. configurable: true
  23169. });
  23170. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23171. /**
  23172. * Set the transparent sort comparison function.
  23173. * If null the sub meshes will be render in the order they were created
  23174. */
  23175. set: function (value) {
  23176. if (value) {
  23177. this._transparentSortCompareFn = value;
  23178. }
  23179. else {
  23180. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23181. }
  23182. this._renderTransparent = this.renderTransparentSorted;
  23183. },
  23184. enumerable: true,
  23185. configurable: true
  23186. });
  23187. /**
  23188. * Render all the sub meshes contained in the group.
  23189. * @param customRenderFunction Used to override the default render behaviour of the group.
  23190. * @returns true if rendered some submeshes.
  23191. */
  23192. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23193. if (customRenderFunction) {
  23194. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23195. return;
  23196. }
  23197. var engine = this._scene.getEngine();
  23198. // Depth only
  23199. if (this._depthOnlySubMeshes.length !== 0) {
  23200. engine.setColorWrite(false);
  23201. this._renderAlphaTest(this._depthOnlySubMeshes);
  23202. engine.setColorWrite(true);
  23203. }
  23204. // Opaque
  23205. if (this._opaqueSubMeshes.length !== 0) {
  23206. this._renderOpaque(this._opaqueSubMeshes);
  23207. }
  23208. // Alpha test
  23209. if (this._alphaTestSubMeshes.length !== 0) {
  23210. this._renderAlphaTest(this._alphaTestSubMeshes);
  23211. }
  23212. var stencilState = engine.getStencilBuffer();
  23213. engine.setStencilBuffer(false);
  23214. // Sprites
  23215. if (renderSprites) {
  23216. this._renderSprites();
  23217. }
  23218. // Particles
  23219. if (renderParticles) {
  23220. this._renderParticles(activeMeshes);
  23221. }
  23222. if (this.onBeforeTransparentRendering) {
  23223. this.onBeforeTransparentRendering();
  23224. }
  23225. // Transparent
  23226. if (this._transparentSubMeshes.length !== 0) {
  23227. this._renderTransparent(this._transparentSubMeshes);
  23228. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23229. }
  23230. // Set back stencil to false in case it changes before the edge renderer.
  23231. engine.setStencilBuffer(false);
  23232. // Edges
  23233. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23234. this._edgesRenderers.data[edgesRendererIndex].render();
  23235. }
  23236. // Restore Stencil state.
  23237. engine.setStencilBuffer(stencilState);
  23238. };
  23239. /**
  23240. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23241. * @param subMeshes The submeshes to render
  23242. */
  23243. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23244. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23245. };
  23246. /**
  23247. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23248. * @param subMeshes The submeshes to render
  23249. */
  23250. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23251. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23252. };
  23253. /**
  23254. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23255. * @param subMeshes The submeshes to render
  23256. */
  23257. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23258. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23259. };
  23260. /**
  23261. * Renders the submeshes in a specified order.
  23262. * @param subMeshes The submeshes to sort before render
  23263. * @param sortCompareFn The comparison function use to sort
  23264. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23265. * @param transparent Specifies to activate blending if true
  23266. */
  23267. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23268. var subIndex = 0;
  23269. var subMesh;
  23270. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23271. for (; subIndex < subMeshes.length; subIndex++) {
  23272. subMesh = subMeshes.data[subIndex];
  23273. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23274. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23275. }
  23276. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23277. if (sortCompareFn) {
  23278. sortedArray.sort(sortCompareFn);
  23279. }
  23280. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23281. subMesh = sortedArray[subIndex];
  23282. if (transparent) {
  23283. var material = subMesh.getMaterial();
  23284. if (material && material.needDepthPrePass) {
  23285. var engine = material.getScene().getEngine();
  23286. engine.setColorWrite(false);
  23287. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23288. subMesh.render(false);
  23289. engine.setColorWrite(true);
  23290. }
  23291. }
  23292. subMesh.render(transparent);
  23293. }
  23294. };
  23295. /**
  23296. * Renders the submeshes in the order they were dispatched (no sort applied).
  23297. * @param subMeshes The submeshes to render
  23298. */
  23299. RenderingGroup.renderUnsorted = function (subMeshes) {
  23300. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23301. var submesh = subMeshes.data[subIndex];
  23302. submesh.render(false);
  23303. }
  23304. };
  23305. /**
  23306. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23307. * are rendered back to front if in the same alpha index.
  23308. *
  23309. * @param a The first submesh
  23310. * @param b The second submesh
  23311. * @returns The result of the comparison
  23312. */
  23313. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23314. // Alpha index first
  23315. if (a._alphaIndex > b._alphaIndex) {
  23316. return 1;
  23317. }
  23318. if (a._alphaIndex < b._alphaIndex) {
  23319. return -1;
  23320. }
  23321. // Then distance to camera
  23322. return RenderingGroup.backToFrontSortCompare(a, b);
  23323. };
  23324. /**
  23325. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23326. * are rendered back to front.
  23327. *
  23328. * @param a The first submesh
  23329. * @param b The second submesh
  23330. * @returns The result of the comparison
  23331. */
  23332. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23333. // Then distance to camera
  23334. if (a._distanceToCamera < b._distanceToCamera) {
  23335. return 1;
  23336. }
  23337. if (a._distanceToCamera > b._distanceToCamera) {
  23338. return -1;
  23339. }
  23340. return 0;
  23341. };
  23342. /**
  23343. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23344. * are rendered front to back (prevent overdraw).
  23345. *
  23346. * @param a The first submesh
  23347. * @param b The second submesh
  23348. * @returns The result of the comparison
  23349. */
  23350. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23351. // Then distance to camera
  23352. if (a._distanceToCamera < b._distanceToCamera) {
  23353. return -1;
  23354. }
  23355. if (a._distanceToCamera > b._distanceToCamera) {
  23356. return 1;
  23357. }
  23358. return 0;
  23359. };
  23360. /**
  23361. * Resets the different lists of submeshes to prepare a new frame.
  23362. */
  23363. RenderingGroup.prototype.prepare = function () {
  23364. this._opaqueSubMeshes.reset();
  23365. this._transparentSubMeshes.reset();
  23366. this._alphaTestSubMeshes.reset();
  23367. this._depthOnlySubMeshes.reset();
  23368. this._particleSystems.reset();
  23369. this._spriteManagers.reset();
  23370. this._edgesRenderers.reset();
  23371. };
  23372. RenderingGroup.prototype.dispose = function () {
  23373. this._opaqueSubMeshes.dispose();
  23374. this._transparentSubMeshes.dispose();
  23375. this._alphaTestSubMeshes.dispose();
  23376. this._depthOnlySubMeshes.dispose();
  23377. this._particleSystems.dispose();
  23378. this._spriteManagers.dispose();
  23379. this._edgesRenderers.dispose();
  23380. };
  23381. /**
  23382. * Inserts the submesh in its correct queue depending on its material.
  23383. * @param subMesh The submesh to dispatch
  23384. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23385. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23386. */
  23387. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23388. // Get mesh and materials if not provided
  23389. if (mesh === undefined) {
  23390. mesh = subMesh.getMesh();
  23391. }
  23392. if (material === undefined) {
  23393. material = subMesh.getMaterial();
  23394. }
  23395. if (material === null || material === undefined) {
  23396. return;
  23397. }
  23398. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23399. this._transparentSubMeshes.push(subMesh);
  23400. }
  23401. else if (material.needAlphaTesting()) { // Alpha test
  23402. if (material.needDepthPrePass) {
  23403. this._depthOnlySubMeshes.push(subMesh);
  23404. }
  23405. this._alphaTestSubMeshes.push(subMesh);
  23406. }
  23407. else {
  23408. if (material.needDepthPrePass) {
  23409. this._depthOnlySubMeshes.push(subMesh);
  23410. }
  23411. this._opaqueSubMeshes.push(subMesh); // Opaque
  23412. }
  23413. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23414. this._edgesRenderers.push(mesh._edgesRenderer);
  23415. }
  23416. };
  23417. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23418. this._spriteManagers.push(spriteManager);
  23419. };
  23420. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23421. this._particleSystems.push(particleSystem);
  23422. };
  23423. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23424. if (this._particleSystems.length === 0) {
  23425. return;
  23426. }
  23427. // Particles
  23428. var activeCamera = this._scene.activeCamera;
  23429. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23430. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23431. var particleSystem = this._particleSystems.data[particleIndex];
  23432. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23433. continue;
  23434. }
  23435. var emitter = particleSystem.emitter;
  23436. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23437. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23438. }
  23439. }
  23440. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23441. };
  23442. RenderingGroup.prototype._renderSprites = function () {
  23443. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23444. return;
  23445. }
  23446. // Sprites
  23447. var activeCamera = this._scene.activeCamera;
  23448. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23449. for (var id = 0; id < this._spriteManagers.length; id++) {
  23450. var spriteManager = this._spriteManagers.data[id];
  23451. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23452. spriteManager.render();
  23453. }
  23454. }
  23455. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23456. };
  23457. return RenderingGroup;
  23458. }());
  23459. BABYLON.RenderingGroup = RenderingGroup;
  23460. })(BABYLON || (BABYLON = {}));
  23461. //# sourceMappingURL=babylon.renderingGroup.js.map
  23462. var BABYLON;
  23463. (function (BABYLON) {
  23464. /** @hidden */
  23465. var ClickInfo = /** @class */ (function () {
  23466. function ClickInfo() {
  23467. this._singleClick = false;
  23468. this._doubleClick = false;
  23469. this._hasSwiped = false;
  23470. this._ignore = false;
  23471. }
  23472. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23473. get: function () {
  23474. return this._singleClick;
  23475. },
  23476. set: function (b) {
  23477. this._singleClick = b;
  23478. },
  23479. enumerable: true,
  23480. configurable: true
  23481. });
  23482. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23483. get: function () {
  23484. return this._doubleClick;
  23485. },
  23486. set: function (b) {
  23487. this._doubleClick = b;
  23488. },
  23489. enumerable: true,
  23490. configurable: true
  23491. });
  23492. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23493. get: function () {
  23494. return this._hasSwiped;
  23495. },
  23496. set: function (b) {
  23497. this._hasSwiped = b;
  23498. },
  23499. enumerable: true,
  23500. configurable: true
  23501. });
  23502. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23503. get: function () {
  23504. return this._ignore;
  23505. },
  23506. set: function (b) {
  23507. this._ignore = b;
  23508. },
  23509. enumerable: true,
  23510. configurable: true
  23511. });
  23512. return ClickInfo;
  23513. }());
  23514. /**
  23515. * This class is used by the onRenderingGroupObservable
  23516. */
  23517. var RenderingGroupInfo = /** @class */ (function () {
  23518. function RenderingGroupInfo() {
  23519. }
  23520. /**
  23521. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23522. * This stage will be fired no matter what
  23523. */
  23524. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23525. /**
  23526. * Called before opaque object are rendered.
  23527. * This stage will be fired only if there's 3D Opaque content to render
  23528. */
  23529. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23530. /**
  23531. * Called after the opaque objects are rendered and before the transparent ones
  23532. * This stage will be fired only if there's 3D transparent content to render
  23533. */
  23534. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23535. /**
  23536. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23537. * This stage will be fired no matter what
  23538. */
  23539. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23540. return RenderingGroupInfo;
  23541. }());
  23542. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23543. /**
  23544. * Represents a scene to be rendered by the engine.
  23545. * @see http://doc.babylonjs.com/features/scene
  23546. */
  23547. var Scene = /** @class */ (function () {
  23548. /**
  23549. * Creates a new Scene
  23550. * @param engine defines the engine to use to render this scene
  23551. */
  23552. function Scene(engine) {
  23553. // Members
  23554. /**
  23555. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23556. */
  23557. this.autoClear = true;
  23558. /**
  23559. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23560. */
  23561. this.autoClearDepthAndStencil = true;
  23562. /**
  23563. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23564. */
  23565. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23566. /**
  23567. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23568. */
  23569. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23570. this._forceWireframe = false;
  23571. this._forcePointsCloud = false;
  23572. /**
  23573. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23574. */
  23575. this.forceShowBoundingBoxes = false;
  23576. /**
  23577. * Gets or sets a boolean indicating if animations are enabled
  23578. */
  23579. this.animationsEnabled = true;
  23580. this._animationPropertiesOverride = null;
  23581. /**
  23582. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23583. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23584. */
  23585. this.useConstantAnimationDeltaTime = false;
  23586. /**
  23587. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23588. * Please note that it requires to run a ray cast through the scene on every frame
  23589. */
  23590. this.constantlyUpdateMeshUnderPointer = false;
  23591. /**
  23592. * Defines the HTML cursor to use when hovering over interactive elements
  23593. */
  23594. this.hoverCursor = "pointer";
  23595. /**
  23596. * Defines the HTML default cursor to use (empty by default)
  23597. */
  23598. this.defaultCursor = "";
  23599. /**
  23600. * This is used to call preventDefault() on pointer down
  23601. * in order to block unwanted artifacts like system double clicks
  23602. */
  23603. this.preventDefaultOnPointerDown = true;
  23604. // Metadata
  23605. /**
  23606. * Gets or sets user defined metadata
  23607. */
  23608. this.metadata = null;
  23609. /**
  23610. * Use this array to add regular expressions used to disable offline support for specific urls
  23611. */
  23612. this.disableOfflineSupportExceptionRules = new Array();
  23613. /**
  23614. * An event triggered when the scene is disposed.
  23615. */
  23616. this.onDisposeObservable = new BABYLON.Observable();
  23617. this._onDisposeObserver = null;
  23618. /**
  23619. * An event triggered before rendering the scene (right after animations and physics)
  23620. */
  23621. this.onBeforeRenderObservable = new BABYLON.Observable();
  23622. this._onBeforeRenderObserver = null;
  23623. /**
  23624. * An event triggered after rendering the scene
  23625. */
  23626. this.onAfterRenderObservable = new BABYLON.Observable();
  23627. this._onAfterRenderObserver = null;
  23628. /**
  23629. * An event triggered before animating the scene
  23630. */
  23631. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23632. /**
  23633. * An event triggered after animations processing
  23634. */
  23635. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23636. /**
  23637. * An event triggered before draw calls are ready to be sent
  23638. */
  23639. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23640. /**
  23641. * An event triggered after draw calls have been sent
  23642. */
  23643. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23644. /**
  23645. * An event triggered when physic simulation is about to be run
  23646. */
  23647. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23648. /**
  23649. * An event triggered when physic simulation has been done
  23650. */
  23651. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23652. /**
  23653. * An event triggered when the scene is ready
  23654. */
  23655. this.onReadyObservable = new BABYLON.Observable();
  23656. /**
  23657. * An event triggered before rendering a camera
  23658. */
  23659. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23660. this._onBeforeCameraRenderObserver = null;
  23661. /**
  23662. * An event triggered after rendering a camera
  23663. */
  23664. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23665. this._onAfterCameraRenderObserver = null;
  23666. /**
  23667. * An event triggered when active meshes evaluation is about to start
  23668. */
  23669. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23670. /**
  23671. * An event triggered when active meshes evaluation is done
  23672. */
  23673. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23674. /**
  23675. * An event triggered when particles rendering is about to start
  23676. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23677. */
  23678. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23679. /**
  23680. * An event triggered when particles rendering is done
  23681. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23682. */
  23683. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23684. /**
  23685. * An event triggered when sprites rendering is about to start
  23686. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23687. */
  23688. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23689. /**
  23690. * An event triggered when sprites rendering is done
  23691. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23692. */
  23693. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23694. /**
  23695. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23696. */
  23697. this.onDataLoadedObservable = new BABYLON.Observable();
  23698. /**
  23699. * An event triggered when a camera is created
  23700. */
  23701. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23702. /**
  23703. * An event triggered when a camera is removed
  23704. */
  23705. this.onCameraRemovedObservable = new BABYLON.Observable();
  23706. /**
  23707. * An event triggered when a light is created
  23708. */
  23709. this.onNewLightAddedObservable = new BABYLON.Observable();
  23710. /**
  23711. * An event triggered when a light is removed
  23712. */
  23713. this.onLightRemovedObservable = new BABYLON.Observable();
  23714. /**
  23715. * An event triggered when a geometry is created
  23716. */
  23717. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23718. /**
  23719. * An event triggered when a geometry is removed
  23720. */
  23721. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23722. /**
  23723. * An event triggered when a transform node is created
  23724. */
  23725. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23726. /**
  23727. * An event triggered when a transform node is removed
  23728. */
  23729. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23730. /**
  23731. * An event triggered when a mesh is created
  23732. */
  23733. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23734. /**
  23735. * An event triggered when a mesh is removed
  23736. */
  23737. this.onMeshRemovedObservable = new BABYLON.Observable();
  23738. /**
  23739. * An event triggered when render targets are about to be rendered
  23740. * Can happen multiple times per frame.
  23741. */
  23742. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23743. /**
  23744. * An event triggered when render targets were rendered.
  23745. * Can happen multiple times per frame.
  23746. */
  23747. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23748. /**
  23749. * An event triggered before calculating deterministic simulation step
  23750. */
  23751. this.onBeforeStepObservable = new BABYLON.Observable();
  23752. /**
  23753. * An event triggered after calculating deterministic simulation step
  23754. */
  23755. this.onAfterStepObservable = new BABYLON.Observable();
  23756. /**
  23757. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23758. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23759. * 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)
  23760. */
  23761. this.onRenderingGroupObservable = new BABYLON.Observable();
  23762. // Animations
  23763. /**
  23764. * Gets a list of Animations associated with the scene
  23765. */
  23766. this.animations = [];
  23767. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23768. /**
  23769. * 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).
  23770. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23771. */
  23772. this.onPrePointerObservable = new BABYLON.Observable();
  23773. /**
  23774. * Observable event triggered each time an input event is received from the rendering canvas
  23775. */
  23776. this.onPointerObservable = new BABYLON.Observable();
  23777. this._meshPickProceed = false;
  23778. this._currentPickResult = null;
  23779. this._previousPickResult = null;
  23780. this._totalPointersPressed = 0;
  23781. this._doubleClickOccured = false;
  23782. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23783. this.cameraToUseForPointers = null;
  23784. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23785. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23786. this._startingPointerTime = 0;
  23787. this._previousStartingPointerTime = 0;
  23788. this._pointerCaptures = {};
  23789. // Deterministic lockstep
  23790. this._timeAccumulator = 0;
  23791. this._currentStepId = 0;
  23792. this._currentInternalStep = 0;
  23793. // Keyboard
  23794. /**
  23795. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23796. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23797. */
  23798. this.onPreKeyboardObservable = new BABYLON.Observable();
  23799. /**
  23800. * Observable event triggered each time an keyboard event is received from the hosting window
  23801. */
  23802. this.onKeyboardObservable = new BABYLON.Observable();
  23803. // Coordinates system
  23804. this._useRightHandedSystem = false;
  23805. // Fog
  23806. this._fogEnabled = true;
  23807. this._fogMode = Scene.FOGMODE_NONE;
  23808. /**
  23809. * Gets or sets the fog color to use
  23810. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23811. */
  23812. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23813. /**
  23814. * Gets or sets the fog density to use
  23815. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23816. */
  23817. this.fogDensity = 0.1;
  23818. /**
  23819. * Gets or sets the fog start distance to use
  23820. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23821. */
  23822. this.fogStart = 0;
  23823. /**
  23824. * Gets or sets the fog end distance to use
  23825. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23826. */
  23827. this.fogEnd = 1000.0;
  23828. // Lights
  23829. this._shadowsEnabled = true;
  23830. this._lightsEnabled = true;
  23831. /**
  23832. * All of the lights added to this scene
  23833. * @see http://doc.babylonjs.com/babylon101/lights
  23834. */
  23835. this.lights = new Array();
  23836. // Cameras
  23837. /** All of the cameras added to this scene.
  23838. * @see http://doc.babylonjs.com/babylon101/cameras
  23839. */
  23840. this.cameras = new Array();
  23841. /** All of the active cameras added to this scene. */
  23842. this.activeCameras = new Array();
  23843. // Meshes
  23844. /**
  23845. * All of the tranform nodes added to this scene
  23846. * @see http://doc.babylonjs.com/how_to/transformnode
  23847. */
  23848. this.transformNodes = new Array();
  23849. /**
  23850. * All of the (abstract) meshes added to this scene
  23851. */
  23852. this.meshes = new Array();
  23853. /**
  23854. * All of the animation groups added to this scene
  23855. * @see http://doc.babylonjs.com/how_to/group
  23856. */
  23857. this.animationGroups = new Array();
  23858. // Geometries
  23859. this._geometries = new Array();
  23860. /**
  23861. * All of the materials added to this scene
  23862. * @see http://doc.babylonjs.com/babylon101/materials
  23863. */
  23864. this.materials = new Array();
  23865. /**
  23866. * All of the multi-materials added to this scene
  23867. * @see http://doc.babylonjs.com/how_to/multi_materials
  23868. */
  23869. this.multiMaterials = new Array();
  23870. // Textures
  23871. this._texturesEnabled = true;
  23872. /**
  23873. * All of the textures added to this scene
  23874. */
  23875. this.textures = new Array();
  23876. // Particles
  23877. /**
  23878. * Gets or sets a boolean indicating if particles are enabled on this scene
  23879. */
  23880. this.particlesEnabled = true;
  23881. /**
  23882. * All of the particle systems added to this scene
  23883. * @see http://doc.babylonjs.com/babylon101/particles
  23884. */
  23885. this.particleSystems = new Array();
  23886. // Sprites
  23887. /**
  23888. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23889. */
  23890. this.spritesEnabled = true;
  23891. /**
  23892. * All of the sprite managers added to this scene
  23893. * @see http://doc.babylonjs.com/babylon101/sprites
  23894. */
  23895. this.spriteManagers = new Array();
  23896. /**
  23897. * The list of layers (background and foreground) of the scene
  23898. */
  23899. this.layers = new Array();
  23900. /**
  23901. * The list of effect layers (highlights/glow) added to the scene
  23902. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23903. * @see http://doc.babylonjs.com/how_to/glow_layer
  23904. */
  23905. this.effectLayers = new Array();
  23906. // Skeletons
  23907. this._skeletonsEnabled = true;
  23908. /**
  23909. * The list of skeletons added to the scene
  23910. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23911. */
  23912. this.skeletons = new Array();
  23913. // Morph targets
  23914. /**
  23915. * The list of morph target managers added to the scene
  23916. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23917. */
  23918. this.morphTargetManagers = new Array();
  23919. // Lens flares
  23920. /**
  23921. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23922. */
  23923. this.lensFlaresEnabled = true;
  23924. /**
  23925. * The list of lens flare system added to the scene
  23926. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23927. */
  23928. this.lensFlareSystems = new Array();
  23929. // Collisions
  23930. /**
  23931. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23932. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23933. */
  23934. this.collisionsEnabled = true;
  23935. /**
  23936. * Defines the gravity applied to this scene (used only for collisions)
  23937. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23938. */
  23939. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23940. // Postprocesses
  23941. /**
  23942. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23943. */
  23944. this.postProcessesEnabled = true;
  23945. /**
  23946. * The list of postprocesses added to the scene
  23947. */
  23948. this.postProcesses = new Array();
  23949. // Customs render targets
  23950. /**
  23951. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23952. */
  23953. this.renderTargetsEnabled = true;
  23954. /**
  23955. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23956. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23957. */
  23958. this.dumpNextRenderTargets = false;
  23959. /**
  23960. * The list of user defined render targets added to the scene
  23961. */
  23962. this.customRenderTargets = new Array();
  23963. /**
  23964. * Gets the list of meshes imported to the scene through SceneLoader
  23965. */
  23966. this.importedMeshesFiles = new Array();
  23967. // Probes
  23968. /**
  23969. * Gets or sets a boolean indicating if probes are enabled on this scene
  23970. */
  23971. this.probesEnabled = true;
  23972. /**
  23973. * The list of reflection probes added to the scene
  23974. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23975. */
  23976. this.reflectionProbes = new Array();
  23977. /** @hidden */
  23978. this._actionManagers = new Array();
  23979. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23980. // Procedural textures
  23981. /**
  23982. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23983. */
  23984. this.proceduralTexturesEnabled = true;
  23985. /**
  23986. * The list of procedural textures added to the scene
  23987. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23988. */
  23989. this.proceduralTextures = new Array();
  23990. /**
  23991. * The list of sound tracks added to the scene
  23992. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23993. */
  23994. this.soundTracks = new Array();
  23995. this._audioEnabled = true;
  23996. this._headphone = false;
  23997. // Performance counters
  23998. this._totalVertices = new BABYLON.PerfCounter();
  23999. /** @hidden */
  24000. this._activeIndices = new BABYLON.PerfCounter();
  24001. /** @hidden */
  24002. this._activeParticles = new BABYLON.PerfCounter();
  24003. /** @hidden */
  24004. this._activeBones = new BABYLON.PerfCounter();
  24005. this._animationTime = 0;
  24006. /**
  24007. * Gets or sets a general scale for animation speed
  24008. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24009. */
  24010. this.animationTimeScale = 1;
  24011. this._renderId = 0;
  24012. this._executeWhenReadyTimeoutId = -1;
  24013. this._intermediateRendering = false;
  24014. this._viewUpdateFlag = -1;
  24015. this._projectionUpdateFlag = -1;
  24016. this._alternateViewUpdateFlag = -1;
  24017. this._alternateProjectionUpdateFlag = -1;
  24018. /** @hidden */
  24019. this._toBeDisposed = new BABYLON.SmartArray(256);
  24020. this._activeRequests = new Array();
  24021. this._pendingData = new Array();
  24022. this._isDisposed = false;
  24023. /**
  24024. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24025. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24026. */
  24027. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24028. this._activeMeshes = new BABYLON.SmartArray(256);
  24029. this._processedMaterials = new BABYLON.SmartArray(256);
  24030. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24031. /** @hidden */
  24032. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24033. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24034. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24035. /** @hidden */
  24036. this._activeAnimatables = new Array();
  24037. this._transformMatrix = BABYLON.Matrix.Zero();
  24038. this._useAlternateCameraConfiguration = false;
  24039. this._alternateRendering = false;
  24040. /**
  24041. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24042. * This is useful if there are more lights that the maximum simulteanous authorized
  24043. */
  24044. this.requireLightSorting = false;
  24045. this._depthRenderer = {};
  24046. this._activeMeshesFrozen = false;
  24047. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24048. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24049. this._engine.scenes.push(this);
  24050. this._uid = null;
  24051. this._renderingManager = new BABYLON.RenderingManager(this);
  24052. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24053. if (BABYLON.OutlineRenderer) {
  24054. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24055. }
  24056. if (BABYLON.Tools.IsWindowObjectExist()) {
  24057. this.attachControl();
  24058. }
  24059. //simplification queue
  24060. if (BABYLON.SimplificationQueue) {
  24061. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24062. }
  24063. //collision coordinator initialization. For now legacy per default.
  24064. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24065. // Uniform Buffer
  24066. this._createUbo();
  24067. // Default Image processing definition.
  24068. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24069. }
  24070. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24071. /** The fog is deactivated */
  24072. get: function () {
  24073. return Scene._FOGMODE_NONE;
  24074. },
  24075. enumerable: true,
  24076. configurable: true
  24077. });
  24078. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24079. /** The fog density is following an exponential function */
  24080. get: function () {
  24081. return Scene._FOGMODE_EXP;
  24082. },
  24083. enumerable: true,
  24084. configurable: true
  24085. });
  24086. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24087. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24088. get: function () {
  24089. return Scene._FOGMODE_EXP2;
  24090. },
  24091. enumerable: true,
  24092. configurable: true
  24093. });
  24094. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24095. /** The fog density is following a linear function. */
  24096. get: function () {
  24097. return Scene._FOGMODE_LINEAR;
  24098. },
  24099. enumerable: true,
  24100. configurable: true
  24101. });
  24102. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24103. /**
  24104. * Texture used in all pbr material as the reflection texture.
  24105. * As in the majority of the scene they are the same (exception for multi room and so on),
  24106. * this is easier to reference from here than from all the materials.
  24107. */
  24108. get: function () {
  24109. return this._environmentTexture;
  24110. },
  24111. /**
  24112. * Texture used in all pbr material as the reflection texture.
  24113. * As in the majority of the scene they are the same (exception for multi room and so on),
  24114. * this is easier to set here than in all the materials.
  24115. */
  24116. set: function (value) {
  24117. if (this._environmentTexture === value) {
  24118. return;
  24119. }
  24120. this._environmentTexture = value;
  24121. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24122. },
  24123. enumerable: true,
  24124. configurable: true
  24125. });
  24126. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24127. /**
  24128. * Default image processing configuration used either in the rendering
  24129. * Forward main pass or through the imageProcessingPostProcess if present.
  24130. * As in the majority of the scene they are the same (exception for multi camera),
  24131. * this is easier to reference from here than from all the materials and post process.
  24132. *
  24133. * No setter as we it is a shared configuration, you can set the values instead.
  24134. */
  24135. get: function () {
  24136. return this._imageProcessingConfiguration;
  24137. },
  24138. enumerable: true,
  24139. configurable: true
  24140. });
  24141. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24142. get: function () {
  24143. return this._forceWireframe;
  24144. },
  24145. /**
  24146. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24147. */
  24148. set: function (value) {
  24149. if (this._forceWireframe === value) {
  24150. return;
  24151. }
  24152. this._forceWireframe = value;
  24153. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24154. },
  24155. enumerable: true,
  24156. configurable: true
  24157. });
  24158. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24159. get: function () {
  24160. return this._forcePointsCloud;
  24161. },
  24162. /**
  24163. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24164. */
  24165. set: function (value) {
  24166. if (this._forcePointsCloud === value) {
  24167. return;
  24168. }
  24169. this._forcePointsCloud = value;
  24170. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24171. },
  24172. enumerable: true,
  24173. configurable: true
  24174. });
  24175. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24176. /**
  24177. * Gets or sets the animation properties override
  24178. */
  24179. get: function () {
  24180. return this._animationPropertiesOverride;
  24181. },
  24182. set: function (value) {
  24183. this._animationPropertiesOverride = value;
  24184. },
  24185. enumerable: true,
  24186. configurable: true
  24187. });
  24188. Object.defineProperty(Scene.prototype, "onDispose", {
  24189. /** Sets a function to be executed when this scene is disposed. */
  24190. set: function (callback) {
  24191. if (this._onDisposeObserver) {
  24192. this.onDisposeObservable.remove(this._onDisposeObserver);
  24193. }
  24194. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24195. },
  24196. enumerable: true,
  24197. configurable: true
  24198. });
  24199. Object.defineProperty(Scene.prototype, "beforeRender", {
  24200. /** Sets a function to be executed before rendering this scene */
  24201. set: function (callback) {
  24202. if (this._onBeforeRenderObserver) {
  24203. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24204. }
  24205. if (callback) {
  24206. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24207. }
  24208. },
  24209. enumerable: true,
  24210. configurable: true
  24211. });
  24212. Object.defineProperty(Scene.prototype, "afterRender", {
  24213. /** Sets a function to be executed after rendering this scene */
  24214. set: function (callback) {
  24215. if (this._onAfterRenderObserver) {
  24216. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24217. }
  24218. if (callback) {
  24219. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24220. }
  24221. },
  24222. enumerable: true,
  24223. configurable: true
  24224. });
  24225. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24226. /** Sets a function to be executed before rendering a camera*/
  24227. set: function (callback) {
  24228. if (this._onBeforeCameraRenderObserver) {
  24229. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24230. }
  24231. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24232. },
  24233. enumerable: true,
  24234. configurable: true
  24235. });
  24236. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24237. /** Sets a function to be executed after rendering a camera*/
  24238. set: function (callback) {
  24239. if (this._onAfterCameraRenderObserver) {
  24240. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24241. }
  24242. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24243. },
  24244. enumerable: true,
  24245. configurable: true
  24246. });
  24247. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24248. /**
  24249. * Gets the gamepad manager associated with the scene
  24250. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24251. */
  24252. get: function () {
  24253. if (!this._gamepadManager) {
  24254. this._gamepadManager = new BABYLON.GamepadManager(this);
  24255. }
  24256. return this._gamepadManager;
  24257. },
  24258. enumerable: true,
  24259. configurable: true
  24260. });
  24261. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24262. /**
  24263. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24264. */
  24265. get: function () {
  24266. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24267. },
  24268. enumerable: true,
  24269. configurable: true
  24270. });
  24271. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24272. get: function () {
  24273. return this._useRightHandedSystem;
  24274. },
  24275. /**
  24276. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24277. */
  24278. set: function (value) {
  24279. if (this._useRightHandedSystem === value) {
  24280. return;
  24281. }
  24282. this._useRightHandedSystem = value;
  24283. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24284. },
  24285. enumerable: true,
  24286. configurable: true
  24287. });
  24288. /**
  24289. * Sets the step Id used by deterministic lock step
  24290. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24291. * @param newStepId defines the step Id
  24292. */
  24293. Scene.prototype.setStepId = function (newStepId) {
  24294. this._currentStepId = newStepId;
  24295. };
  24296. ;
  24297. /**
  24298. * Gets the step Id used by deterministic lock step
  24299. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24300. * @returns the step Id
  24301. */
  24302. Scene.prototype.getStepId = function () {
  24303. return this._currentStepId;
  24304. };
  24305. ;
  24306. /**
  24307. * Gets the internal step used by deterministic lock step
  24308. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24309. * @returns the internal step
  24310. */
  24311. Scene.prototype.getInternalStep = function () {
  24312. return this._currentInternalStep;
  24313. };
  24314. ;
  24315. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24316. get: function () {
  24317. return this._fogEnabled;
  24318. },
  24319. /**
  24320. * Gets or sets a boolean indicating if fog is enabled on this scene
  24321. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24322. */
  24323. set: function (value) {
  24324. if (this._fogEnabled === value) {
  24325. return;
  24326. }
  24327. this._fogEnabled = value;
  24328. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24329. },
  24330. enumerable: true,
  24331. configurable: true
  24332. });
  24333. Object.defineProperty(Scene.prototype, "fogMode", {
  24334. get: function () {
  24335. return this._fogMode;
  24336. },
  24337. /**
  24338. * Gets or sets the fog mode to use
  24339. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24340. */
  24341. set: function (value) {
  24342. if (this._fogMode === value) {
  24343. return;
  24344. }
  24345. this._fogMode = value;
  24346. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24347. },
  24348. enumerable: true,
  24349. configurable: true
  24350. });
  24351. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24352. get: function () {
  24353. return this._shadowsEnabled;
  24354. },
  24355. /**
  24356. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24357. */
  24358. set: function (value) {
  24359. if (this._shadowsEnabled === value) {
  24360. return;
  24361. }
  24362. this._shadowsEnabled = value;
  24363. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24364. },
  24365. enumerable: true,
  24366. configurable: true
  24367. });
  24368. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24369. get: function () {
  24370. return this._lightsEnabled;
  24371. },
  24372. /**
  24373. * Gets or sets a boolean indicating if lights are enabled on this scene
  24374. */
  24375. set: function (value) {
  24376. if (this._lightsEnabled === value) {
  24377. return;
  24378. }
  24379. this._lightsEnabled = value;
  24380. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24381. },
  24382. enumerable: true,
  24383. configurable: true
  24384. });
  24385. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24386. /** The default material used on meshes when no material is affected */
  24387. get: function () {
  24388. if (!this._defaultMaterial) {
  24389. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24390. }
  24391. return this._defaultMaterial;
  24392. },
  24393. /** The default material used on meshes when no material is affected */
  24394. set: function (value) {
  24395. this._defaultMaterial = value;
  24396. },
  24397. enumerable: true,
  24398. configurable: true
  24399. });
  24400. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24401. get: function () {
  24402. return this._texturesEnabled;
  24403. },
  24404. /**
  24405. * Gets or sets a boolean indicating if textures are enabled on this scene
  24406. */
  24407. set: function (value) {
  24408. if (this._texturesEnabled === value) {
  24409. return;
  24410. }
  24411. this._texturesEnabled = value;
  24412. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24413. },
  24414. enumerable: true,
  24415. configurable: true
  24416. });
  24417. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24418. get: function () {
  24419. return this._skeletonsEnabled;
  24420. },
  24421. /**
  24422. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24423. */
  24424. set: function (value) {
  24425. if (this._skeletonsEnabled === value) {
  24426. return;
  24427. }
  24428. this._skeletonsEnabled = value;
  24429. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24430. },
  24431. enumerable: true,
  24432. configurable: true
  24433. });
  24434. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24435. /**
  24436. * Gets the postprocess render pipeline manager
  24437. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24438. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24439. */
  24440. get: function () {
  24441. if (!this._postProcessRenderPipelineManager) {
  24442. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24443. }
  24444. return this._postProcessRenderPipelineManager;
  24445. },
  24446. enumerable: true,
  24447. configurable: true
  24448. });
  24449. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24450. /**
  24451. * Gets the main soundtrack associated with the scene
  24452. */
  24453. get: function () {
  24454. if (!this._mainSoundTrack) {
  24455. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24456. }
  24457. return this._mainSoundTrack;
  24458. },
  24459. enumerable: true,
  24460. configurable: true
  24461. });
  24462. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24463. /** @hidden */
  24464. get: function () {
  24465. return this._alternateRendering;
  24466. },
  24467. enumerable: true,
  24468. configurable: true
  24469. });
  24470. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24471. /**
  24472. * Gets the list of frustum planes (built from the active camera)
  24473. */
  24474. get: function () {
  24475. return this._frustumPlanes;
  24476. },
  24477. enumerable: true,
  24478. configurable: true
  24479. });
  24480. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24481. /**
  24482. * Gets the current geometry buffer associated to the scene.
  24483. */
  24484. get: function () {
  24485. return this._geometryBufferRenderer;
  24486. },
  24487. /**
  24488. * Sets the current geometry buffer for the scene.
  24489. */
  24490. set: function (geometryBufferRenderer) {
  24491. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24492. this._geometryBufferRenderer = geometryBufferRenderer;
  24493. }
  24494. },
  24495. enumerable: true,
  24496. configurable: true
  24497. });
  24498. Object.defineProperty(Scene.prototype, "debugLayer", {
  24499. /**
  24500. * Gets the debug layer associated with the scene
  24501. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24502. */
  24503. get: function () {
  24504. if (!this._debugLayer) {
  24505. this._debugLayer = new BABYLON.DebugLayer(this);
  24506. }
  24507. return this._debugLayer;
  24508. },
  24509. enumerable: true,
  24510. configurable: true
  24511. });
  24512. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24513. /**
  24514. * Gets a boolean indicating if collisions are processed on a web worker
  24515. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24516. */
  24517. get: function () {
  24518. return this._workerCollisions;
  24519. },
  24520. set: function (enabled) {
  24521. if (!BABYLON.CollisionCoordinatorLegacy) {
  24522. return;
  24523. }
  24524. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24525. this._workerCollisions = enabled;
  24526. if (this.collisionCoordinator) {
  24527. this.collisionCoordinator.destroy();
  24528. }
  24529. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24530. this.collisionCoordinator.init(this);
  24531. },
  24532. enumerable: true,
  24533. configurable: true
  24534. });
  24535. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24536. /**
  24537. * Gets the octree used to boost mesh selection (picking)
  24538. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24539. */
  24540. get: function () {
  24541. return this._selectionOctree;
  24542. },
  24543. enumerable: true,
  24544. configurable: true
  24545. });
  24546. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24547. /**
  24548. * Gets the mesh that is currently under the pointer
  24549. */
  24550. get: function () {
  24551. return this._pointerOverMesh;
  24552. },
  24553. enumerable: true,
  24554. configurable: true
  24555. });
  24556. Object.defineProperty(Scene.prototype, "pointerX", {
  24557. /**
  24558. * Gets the current on-screen X position of the pointer
  24559. */
  24560. get: function () {
  24561. return this._pointerX;
  24562. },
  24563. enumerable: true,
  24564. configurable: true
  24565. });
  24566. Object.defineProperty(Scene.prototype, "pointerY", {
  24567. /**
  24568. * Gets the current on-screen Y position of the pointer
  24569. */
  24570. get: function () {
  24571. return this._pointerY;
  24572. },
  24573. enumerable: true,
  24574. configurable: true
  24575. });
  24576. /**
  24577. * Gets the cached material (ie. the latest rendered one)
  24578. * @returns the cached material
  24579. */
  24580. Scene.prototype.getCachedMaterial = function () {
  24581. return this._cachedMaterial;
  24582. };
  24583. /**
  24584. * Gets the cached effect (ie. the latest rendered one)
  24585. * @returns the cached effect
  24586. */
  24587. Scene.prototype.getCachedEffect = function () {
  24588. return this._cachedEffect;
  24589. };
  24590. /**
  24591. * Gets the cached visibility state (ie. the latest rendered one)
  24592. * @returns the cached visibility state
  24593. */
  24594. Scene.prototype.getCachedVisibility = function () {
  24595. return this._cachedVisibility;
  24596. };
  24597. /**
  24598. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24599. * @param material defines the current material
  24600. * @param effect defines the current effect
  24601. * @param visibility defines the current visibility state
  24602. * @returns true if one parameter is not cached
  24603. */
  24604. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24605. if (visibility === void 0) { visibility = 1; }
  24606. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24607. };
  24608. /**
  24609. * Gets the bounding box renderer associated with the scene
  24610. * @returns a BoundingBoxRenderer
  24611. */
  24612. Scene.prototype.getBoundingBoxRenderer = function () {
  24613. if (!this._boundingBoxRenderer) {
  24614. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24615. }
  24616. return this._boundingBoxRenderer;
  24617. };
  24618. /**
  24619. * Gets the outline renderer associated with the scene
  24620. * @returns a OutlineRenderer
  24621. */
  24622. Scene.prototype.getOutlineRenderer = function () {
  24623. return this._outlineRenderer;
  24624. };
  24625. /**
  24626. * Gets the engine associated with the scene
  24627. * @returns an Engine
  24628. */
  24629. Scene.prototype.getEngine = function () {
  24630. return this._engine;
  24631. };
  24632. /**
  24633. * Gets the total number of vertices rendered per frame
  24634. * @returns the total number of vertices rendered per frame
  24635. */
  24636. Scene.prototype.getTotalVertices = function () {
  24637. return this._totalVertices.current;
  24638. };
  24639. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24640. /**
  24641. * Gets the performance counter for total vertices
  24642. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24643. */
  24644. get: function () {
  24645. return this._totalVertices;
  24646. },
  24647. enumerable: true,
  24648. configurable: true
  24649. });
  24650. /**
  24651. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24652. * @returns the total number of active indices rendered per frame
  24653. */
  24654. Scene.prototype.getActiveIndices = function () {
  24655. return this._activeIndices.current;
  24656. };
  24657. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24658. /**
  24659. * Gets the performance counter for active indices
  24660. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24661. */
  24662. get: function () {
  24663. return this._activeIndices;
  24664. },
  24665. enumerable: true,
  24666. configurable: true
  24667. });
  24668. /**
  24669. * Gets the total number of active particles rendered per frame
  24670. * @returns the total number of active particles rendered per frame
  24671. */
  24672. Scene.prototype.getActiveParticles = function () {
  24673. return this._activeParticles.current;
  24674. };
  24675. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24676. /**
  24677. * Gets the performance counter for active particles
  24678. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24679. */
  24680. get: function () {
  24681. return this._activeParticles;
  24682. },
  24683. enumerable: true,
  24684. configurable: true
  24685. });
  24686. /**
  24687. * Gets the total number of active bones rendered per frame
  24688. * @returns the total number of active bones rendered per frame
  24689. */
  24690. Scene.prototype.getActiveBones = function () {
  24691. return this._activeBones.current;
  24692. };
  24693. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24694. /**
  24695. * Gets the performance counter for active bones
  24696. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24697. */
  24698. get: function () {
  24699. return this._activeBones;
  24700. },
  24701. enumerable: true,
  24702. configurable: true
  24703. });
  24704. /** @hidden */
  24705. Scene.prototype.getInterFramePerfCounter = function () {
  24706. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24707. return 0;
  24708. };
  24709. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24710. /** @hidden */
  24711. get: function () {
  24712. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24713. return null;
  24714. },
  24715. enumerable: true,
  24716. configurable: true
  24717. });
  24718. /** @hidden */
  24719. Scene.prototype.getLastFrameDuration = function () {
  24720. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24721. return 0;
  24722. };
  24723. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24724. /** @hidden */
  24725. get: function () {
  24726. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24727. return null;
  24728. },
  24729. enumerable: true,
  24730. configurable: true
  24731. });
  24732. /** @hidden */
  24733. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24734. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24735. return 0;
  24736. };
  24737. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24738. /** @hidden */
  24739. get: function () {
  24740. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24741. return null;
  24742. },
  24743. enumerable: true,
  24744. configurable: true
  24745. });
  24746. /**
  24747. * Gets the array of active meshes
  24748. * @returns an array of AbstractMesh
  24749. */
  24750. Scene.prototype.getActiveMeshes = function () {
  24751. return this._activeMeshes;
  24752. };
  24753. /** @hidden */
  24754. Scene.prototype.getRenderTargetsDuration = function () {
  24755. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24756. return 0;
  24757. };
  24758. /** @hidden */
  24759. Scene.prototype.getRenderDuration = function () {
  24760. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24761. return 0;
  24762. };
  24763. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24764. /** @hidden */
  24765. get: function () {
  24766. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24767. return null;
  24768. },
  24769. enumerable: true,
  24770. configurable: true
  24771. });
  24772. /** @hidden */
  24773. Scene.prototype.getParticlesDuration = function () {
  24774. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24775. return 0;
  24776. };
  24777. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24778. /** @hidden */
  24779. get: function () {
  24780. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24781. return null;
  24782. },
  24783. enumerable: true,
  24784. configurable: true
  24785. });
  24786. /** @hidden */
  24787. Scene.prototype.getSpritesDuration = function () {
  24788. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24789. return 0;
  24790. };
  24791. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24792. /** @hidden */
  24793. get: function () {
  24794. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24795. return null;
  24796. },
  24797. enumerable: true,
  24798. configurable: true
  24799. });
  24800. /**
  24801. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24802. * @returns a number
  24803. */
  24804. Scene.prototype.getAnimationRatio = function () {
  24805. return this._animationRatio;
  24806. };
  24807. /**
  24808. * Gets an unique Id for the current frame
  24809. * @returns a number
  24810. */
  24811. Scene.prototype.getRenderId = function () {
  24812. return this._renderId;
  24813. };
  24814. /** Call this function if you want to manually increment the render Id*/
  24815. Scene.prototype.incrementRenderId = function () {
  24816. this._renderId++;
  24817. };
  24818. Scene.prototype._updatePointerPosition = function (evt) {
  24819. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24820. if (!canvasRect) {
  24821. return;
  24822. }
  24823. this._pointerX = evt.clientX - canvasRect.left;
  24824. this._pointerY = evt.clientY - canvasRect.top;
  24825. this._unTranslatedPointerX = this._pointerX;
  24826. this._unTranslatedPointerY = this._pointerY;
  24827. };
  24828. Scene.prototype._createUbo = function () {
  24829. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24830. this._sceneUbo.addUniform("viewProjection", 16);
  24831. this._sceneUbo.addUniform("view", 16);
  24832. };
  24833. Scene.prototype._createAlternateUbo = function () {
  24834. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24835. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24836. this._alternateSceneUbo.addUniform("view", 16);
  24837. };
  24838. // Pointers handling
  24839. /**
  24840. * Use this method to simulate a pointer move on a mesh
  24841. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24842. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24843. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24844. * @returns the current scene
  24845. */
  24846. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24847. var evt = new PointerEvent("pointermove", pointerEventInit);
  24848. return this._processPointerMove(pickResult, evt);
  24849. };
  24850. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24851. var canvas = this._engine.getRenderingCanvas();
  24852. if (!canvas) {
  24853. return this;
  24854. }
  24855. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24856. this.setPointerOverSprite(null);
  24857. this.setPointerOverMesh(pickResult.pickedMesh);
  24858. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24859. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24860. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24861. }
  24862. else {
  24863. canvas.style.cursor = this.hoverCursor;
  24864. }
  24865. }
  24866. else {
  24867. canvas.style.cursor = this.defaultCursor;
  24868. }
  24869. }
  24870. else {
  24871. this.setPointerOverMesh(null);
  24872. // Sprites
  24873. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24874. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24875. this.setPointerOverSprite(pickResult.pickedSprite);
  24876. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24877. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24878. }
  24879. else {
  24880. canvas.style.cursor = this.hoverCursor;
  24881. }
  24882. }
  24883. else {
  24884. this.setPointerOverSprite(null);
  24885. // Restore pointer
  24886. canvas.style.cursor = this.defaultCursor;
  24887. }
  24888. }
  24889. if (pickResult) {
  24890. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24891. if (this.onPointerMove) {
  24892. this.onPointerMove(evt, pickResult, type);
  24893. }
  24894. if (this.onPointerObservable.hasObservers()) {
  24895. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24896. this.onPointerObservable.notifyObservers(pi, type);
  24897. }
  24898. }
  24899. return this;
  24900. };
  24901. /**
  24902. * Use this method to simulate a pointer down on a mesh
  24903. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24904. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24905. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24906. * @returns the current scene
  24907. */
  24908. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24909. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24910. return this._processPointerDown(pickResult, evt);
  24911. };
  24912. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24913. var _this = this;
  24914. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24915. this._pickedDownMesh = pickResult.pickedMesh;
  24916. var actionManager = pickResult.pickedMesh.actionManager;
  24917. if (actionManager) {
  24918. if (actionManager.hasPickTriggers) {
  24919. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24920. switch (evt.button) {
  24921. case 0:
  24922. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24923. break;
  24924. case 1:
  24925. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24926. break;
  24927. case 2:
  24928. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24929. break;
  24930. }
  24931. }
  24932. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24933. window.setTimeout(function () {
  24934. 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);
  24935. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24936. if (_this._totalPointersPressed !== 0 &&
  24937. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24938. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24939. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24940. _this._startingPointerTime = 0;
  24941. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24942. }
  24943. }
  24944. }, Scene.LongPressDelay);
  24945. }
  24946. }
  24947. }
  24948. if (pickResult) {
  24949. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24950. if (this.onPointerDown) {
  24951. this.onPointerDown(evt, pickResult, type);
  24952. }
  24953. if (this.onPointerObservable.hasObservers()) {
  24954. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24955. this.onPointerObservable.notifyObservers(pi, type);
  24956. }
  24957. }
  24958. return this;
  24959. };
  24960. /**
  24961. * Use this method to simulate a pointer up on a mesh
  24962. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24963. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24964. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24965. * @returns the current scene
  24966. */
  24967. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24968. var evt = new PointerEvent("pointerup", pointerEventInit);
  24969. var clickInfo = new ClickInfo();
  24970. clickInfo.singleClick = true;
  24971. clickInfo.ignore = true;
  24972. return this._processPointerUp(pickResult, evt, clickInfo);
  24973. };
  24974. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24975. if (pickResult && pickResult && pickResult.pickedMesh) {
  24976. this._pickedUpMesh = pickResult.pickedMesh;
  24977. if (this._pickedDownMesh === this._pickedUpMesh) {
  24978. if (this.onPointerPick) {
  24979. this.onPointerPick(evt, pickResult);
  24980. }
  24981. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24982. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24983. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24984. this.onPointerObservable.notifyObservers(pi, type_1);
  24985. }
  24986. }
  24987. if (pickResult.pickedMesh.actionManager) {
  24988. if (clickInfo.ignore) {
  24989. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24990. }
  24991. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24992. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24993. }
  24994. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24995. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24996. }
  24997. }
  24998. }
  24999. if (this._pickedDownMesh &&
  25000. this._pickedDownMesh.actionManager &&
  25001. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25002. this._pickedDownMesh !== this._pickedUpMesh) {
  25003. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25004. }
  25005. var type = BABYLON.PointerEventTypes.POINTERUP;
  25006. if (this.onPointerObservable.hasObservers()) {
  25007. if (!clickInfo.ignore) {
  25008. if (!clickInfo.hasSwiped) {
  25009. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25010. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25011. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25012. this.onPointerObservable.notifyObservers(pi, type_2);
  25013. }
  25014. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25015. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25016. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25017. this.onPointerObservable.notifyObservers(pi, type_3);
  25018. }
  25019. }
  25020. }
  25021. else {
  25022. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25023. this.onPointerObservable.notifyObservers(pi, type);
  25024. }
  25025. }
  25026. if (this.onPointerUp) {
  25027. this.onPointerUp(evt, pickResult, type);
  25028. }
  25029. return this;
  25030. };
  25031. /**
  25032. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25033. * @param attachUp defines if you want to attach events to pointerup
  25034. * @param attachDown defines if you want to attach events to pointerdown
  25035. * @param attachMove defines if you want to attach events to pointermove
  25036. */
  25037. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25038. var _this = this;
  25039. if (attachUp === void 0) { attachUp = true; }
  25040. if (attachDown === void 0) { attachDown = true; }
  25041. if (attachMove === void 0) { attachMove = true; }
  25042. this._initActionManager = function (act, clickInfo) {
  25043. if (!_this._meshPickProceed) {
  25044. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25045. _this._currentPickResult = pickResult;
  25046. if (pickResult) {
  25047. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25048. }
  25049. _this._meshPickProceed = true;
  25050. }
  25051. return act;
  25052. };
  25053. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25054. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25055. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25056. btn !== _this._previousButtonPressed) {
  25057. _this._doubleClickOccured = false;
  25058. clickInfo.singleClick = true;
  25059. clickInfo.ignore = false;
  25060. cb(clickInfo, _this._currentPickResult);
  25061. }
  25062. };
  25063. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25064. var clickInfo = new ClickInfo();
  25065. _this._currentPickResult = null;
  25066. var act = null;
  25067. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25068. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25069. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25070. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25071. act = _this._initActionManager(act, clickInfo);
  25072. if (act)
  25073. checkPicking = act.hasPickTriggers;
  25074. }
  25075. if (checkPicking) {
  25076. var btn = evt.button;
  25077. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25078. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25079. if (!clickInfo.hasSwiped) {
  25080. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25081. if (!checkSingleClickImmediately) {
  25082. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25083. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25084. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25085. act = _this._initActionManager(act, clickInfo);
  25086. if (act)
  25087. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25088. }
  25089. }
  25090. if (checkSingleClickImmediately) {
  25091. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25092. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25093. btn !== _this._previousButtonPressed) {
  25094. clickInfo.singleClick = true;
  25095. cb(clickInfo, _this._currentPickResult);
  25096. }
  25097. }
  25098. // at least one double click is required to be check and exclusive double click is enabled
  25099. else {
  25100. // wait that no double click has been raised during the double click delay
  25101. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25102. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25103. }
  25104. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25105. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25106. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25107. act = _this._initActionManager(act, clickInfo);
  25108. if (act)
  25109. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25110. }
  25111. if (checkDoubleClick) {
  25112. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25113. if (btn === _this._previousButtonPressed &&
  25114. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25115. !_this._doubleClickOccured) {
  25116. // pointer has not moved for 2 clicks, it's a double click
  25117. if (!clickInfo.hasSwiped &&
  25118. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25119. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25120. _this._previousStartingPointerTime = 0;
  25121. _this._doubleClickOccured = true;
  25122. clickInfo.doubleClick = true;
  25123. clickInfo.ignore = false;
  25124. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25125. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25126. }
  25127. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25128. cb(clickInfo, _this._currentPickResult);
  25129. }
  25130. // if the two successive clicks are too far, it's just two simple clicks
  25131. else {
  25132. _this._doubleClickOccured = false;
  25133. _this._previousStartingPointerTime = _this._startingPointerTime;
  25134. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25135. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25136. _this._previousButtonPressed = btn;
  25137. if (Scene.ExclusiveDoubleClickMode) {
  25138. if (_this._previousDelayedSimpleClickTimeout) {
  25139. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25140. }
  25141. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25142. cb(clickInfo, _this._previousPickResult);
  25143. }
  25144. else {
  25145. cb(clickInfo, _this._currentPickResult);
  25146. }
  25147. }
  25148. }
  25149. // just the first click of the double has been raised
  25150. else {
  25151. _this._doubleClickOccured = false;
  25152. _this._previousStartingPointerTime = _this._startingPointerTime;
  25153. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25154. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25155. _this._previousButtonPressed = btn;
  25156. }
  25157. }
  25158. }
  25159. }
  25160. clickInfo.ignore = true;
  25161. cb(clickInfo, _this._currentPickResult);
  25162. };
  25163. this._spritePredicate = function (sprite) {
  25164. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25165. };
  25166. this._onPointerMove = function (evt) {
  25167. _this._updatePointerPosition(evt);
  25168. // PreObservable support
  25169. if (_this.onPrePointerObservable.hasObservers() && !_this._pointerCaptures[evt.pointerId]) {
  25170. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25171. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25172. _this.onPrePointerObservable.notifyObservers(pi, type);
  25173. if (pi.skipOnPointerObservable) {
  25174. return;
  25175. }
  25176. }
  25177. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25178. return;
  25179. }
  25180. if (!_this.pointerMovePredicate) {
  25181. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25182. }
  25183. // Meshes
  25184. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25185. _this._processPointerMove(pickResult, evt);
  25186. };
  25187. this._onPointerDown = function (evt) {
  25188. _this._totalPointersPressed++;
  25189. _this._pickedDownMesh = null;
  25190. _this._meshPickProceed = false;
  25191. _this._updatePointerPosition(evt);
  25192. if (_this.preventDefaultOnPointerDown && canvas) {
  25193. evt.preventDefault();
  25194. canvas.focus();
  25195. }
  25196. // PreObservable support
  25197. if (_this.onPrePointerObservable.hasObservers()) {
  25198. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25199. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25200. _this.onPrePointerObservable.notifyObservers(pi, type);
  25201. if (pi.skipOnPointerObservable) {
  25202. return;
  25203. }
  25204. }
  25205. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25206. return;
  25207. }
  25208. _this._pointerCaptures[evt.pointerId] = true;
  25209. _this._startingPointerPosition.x = _this._pointerX;
  25210. _this._startingPointerPosition.y = _this._pointerY;
  25211. _this._startingPointerTime = Date.now();
  25212. if (!_this.pointerDownPredicate) {
  25213. _this.pointerDownPredicate = function (mesh) {
  25214. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25215. };
  25216. }
  25217. // Meshes
  25218. _this._pickedDownMesh = null;
  25219. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25220. _this._processPointerDown(pickResult, evt);
  25221. // Sprites
  25222. _this._pickedDownSprite = null;
  25223. if (_this.spriteManagers.length > 0) {
  25224. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25225. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25226. if (pickResult.pickedSprite.actionManager) {
  25227. _this._pickedDownSprite = pickResult.pickedSprite;
  25228. switch (evt.button) {
  25229. case 0:
  25230. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25231. break;
  25232. case 1:
  25233. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25234. break;
  25235. case 2:
  25236. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25237. break;
  25238. }
  25239. if (pickResult.pickedSprite.actionManager) {
  25240. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25241. }
  25242. }
  25243. }
  25244. }
  25245. };
  25246. this._onPointerUp = function (evt) {
  25247. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25248. return; // So we need to test it the pointer down was pressed before.
  25249. }
  25250. _this._totalPointersPressed--;
  25251. _this._pickedUpMesh = null;
  25252. _this._meshPickProceed = false;
  25253. _this._updatePointerPosition(evt);
  25254. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25255. // PreObservable support
  25256. if (_this.onPrePointerObservable.hasObservers() && !_this._pointerCaptures[evt.pointerId]) {
  25257. if (!clickInfo.ignore) {
  25258. if (!clickInfo.hasSwiped) {
  25259. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25260. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25261. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25262. _this.onPrePointerObservable.notifyObservers(pi, type);
  25263. if (pi.skipOnPointerObservable) {
  25264. return;
  25265. }
  25266. }
  25267. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25268. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25269. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25270. _this.onPrePointerObservable.notifyObservers(pi, type);
  25271. if (pi.skipOnPointerObservable) {
  25272. return;
  25273. }
  25274. }
  25275. }
  25276. }
  25277. else {
  25278. var type = BABYLON.PointerEventTypes.POINTERUP;
  25279. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25280. _this.onPrePointerObservable.notifyObservers(pi, type);
  25281. if (pi.skipOnPointerObservable) {
  25282. return;
  25283. }
  25284. }
  25285. }
  25286. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25287. return;
  25288. }
  25289. _this._pointerCaptures[evt.pointerId] = false;
  25290. if (!_this.pointerUpPredicate) {
  25291. _this.pointerUpPredicate = function (mesh) {
  25292. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25293. };
  25294. }
  25295. // Meshes
  25296. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25297. _this._initActionManager(null, clickInfo);
  25298. }
  25299. if (!pickResult) {
  25300. pickResult = _this._currentPickResult;
  25301. }
  25302. _this._processPointerUp(pickResult, evt, clickInfo);
  25303. // Sprites
  25304. if (!clickInfo.ignore) {
  25305. if (_this.spriteManagers.length > 0) {
  25306. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25307. if (spritePickResult) {
  25308. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25309. if (spritePickResult.pickedSprite.actionManager) {
  25310. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25311. if (spritePickResult.pickedSprite.actionManager) {
  25312. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25313. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25314. }
  25315. }
  25316. }
  25317. }
  25318. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25319. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25320. }
  25321. }
  25322. }
  25323. }
  25324. _this._previousPickResult = _this._currentPickResult;
  25325. });
  25326. };
  25327. this._onKeyDown = function (evt) {
  25328. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25329. if (_this.onPreKeyboardObservable.hasObservers()) {
  25330. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25331. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25332. if (pi.skipOnPointerObservable) {
  25333. return;
  25334. }
  25335. }
  25336. if (_this.onKeyboardObservable.hasObservers()) {
  25337. var pi = new BABYLON.KeyboardInfo(type, evt);
  25338. _this.onKeyboardObservable.notifyObservers(pi, type);
  25339. }
  25340. if (_this.actionManager) {
  25341. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25342. }
  25343. };
  25344. this._onKeyUp = function (evt) {
  25345. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25346. if (_this.onPreKeyboardObservable.hasObservers()) {
  25347. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25348. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25349. if (pi.skipOnPointerObservable) {
  25350. return;
  25351. }
  25352. }
  25353. if (_this.onKeyboardObservable.hasObservers()) {
  25354. var pi = new BABYLON.KeyboardInfo(type, evt);
  25355. _this.onKeyboardObservable.notifyObservers(pi, type);
  25356. }
  25357. if (_this.actionManager) {
  25358. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25359. }
  25360. };
  25361. var engine = this.getEngine();
  25362. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25363. if (!canvas) {
  25364. return;
  25365. }
  25366. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25367. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25368. });
  25369. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25370. if (!canvas) {
  25371. return;
  25372. }
  25373. canvas.removeEventListener("keydown", _this._onKeyDown);
  25374. canvas.removeEventListener("keyup", _this._onKeyUp);
  25375. });
  25376. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25377. var canvas = this._engine.getRenderingCanvas();
  25378. if (!canvas) {
  25379. return;
  25380. }
  25381. if (attachMove) {
  25382. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25383. // Wheel
  25384. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25385. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25386. }
  25387. if (attachDown) {
  25388. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25389. }
  25390. if (attachUp) {
  25391. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25392. }
  25393. canvas.tabIndex = 1;
  25394. };
  25395. /** Detaches all event handlers*/
  25396. Scene.prototype.detachControl = function () {
  25397. var engine = this.getEngine();
  25398. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25399. var canvas = engine.getRenderingCanvas();
  25400. if (!canvas) {
  25401. return;
  25402. }
  25403. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25404. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25405. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25406. if (this._onCanvasBlurObserver) {
  25407. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25408. }
  25409. if (this._onCanvasFocusObserver) {
  25410. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25411. }
  25412. // Wheel
  25413. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25414. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25415. // Keyboard
  25416. canvas.removeEventListener("keydown", this._onKeyDown);
  25417. canvas.removeEventListener("keyup", this._onKeyUp);
  25418. // Observables
  25419. this.onKeyboardObservable.clear();
  25420. this.onPreKeyboardObservable.clear();
  25421. this.onPointerObservable.clear();
  25422. this.onPrePointerObservable.clear();
  25423. };
  25424. /**
  25425. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25426. * Delay loaded resources are not taking in account
  25427. * @return true if all required resources are ready
  25428. */
  25429. Scene.prototype.isReady = function () {
  25430. if (this._isDisposed) {
  25431. return false;
  25432. }
  25433. if (this._pendingData.length > 0) {
  25434. return false;
  25435. }
  25436. var index;
  25437. var engine = this.getEngine();
  25438. // Geometries
  25439. for (index = 0; index < this._geometries.length; index++) {
  25440. var geometry = this._geometries[index];
  25441. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25442. return false;
  25443. }
  25444. }
  25445. // Meshes
  25446. for (index = 0; index < this.meshes.length; index++) {
  25447. var mesh = this.meshes[index];
  25448. if (!mesh.isEnabled()) {
  25449. continue;
  25450. }
  25451. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25452. continue;
  25453. }
  25454. if (!mesh.isReady(true)) {
  25455. return false;
  25456. }
  25457. // Effect layers
  25458. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25459. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25460. var layer = _a[_i];
  25461. if (!layer.hasMesh(mesh)) {
  25462. continue;
  25463. }
  25464. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25465. var subMesh = _c[_b];
  25466. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25467. return false;
  25468. }
  25469. }
  25470. }
  25471. }
  25472. // Post-processes
  25473. if (this.activeCameras && this.activeCameras.length > 0) {
  25474. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25475. var camera = _e[_d];
  25476. if (!camera.isReady(true)) {
  25477. return false;
  25478. }
  25479. }
  25480. }
  25481. else if (this.activeCamera) {
  25482. if (!this.activeCamera.isReady(true)) {
  25483. return false;
  25484. }
  25485. }
  25486. // Particles
  25487. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25488. var particleSystem = _g[_f];
  25489. if (!particleSystem.isReady()) {
  25490. return false;
  25491. }
  25492. }
  25493. return true;
  25494. };
  25495. /** Resets all cached information relative to material (including effect and visibility) */
  25496. Scene.prototype.resetCachedMaterial = function () {
  25497. this._cachedMaterial = null;
  25498. this._cachedEffect = null;
  25499. this._cachedVisibility = null;
  25500. };
  25501. /**
  25502. * Registers a function to be called before every frame render
  25503. * @param func defines the function to register
  25504. */
  25505. Scene.prototype.registerBeforeRender = function (func) {
  25506. this.onBeforeRenderObservable.add(func);
  25507. };
  25508. /**
  25509. * Unregisters a function called before every frame render
  25510. * @param func defines the function to unregister
  25511. */
  25512. Scene.prototype.unregisterBeforeRender = function (func) {
  25513. this.onBeforeRenderObservable.removeCallback(func);
  25514. };
  25515. /**
  25516. * Registers a function to be called after every frame render
  25517. * @param func defines the function to register
  25518. */
  25519. Scene.prototype.registerAfterRender = function (func) {
  25520. this.onAfterRenderObservable.add(func);
  25521. };
  25522. /**
  25523. * Unregisters a function called after every frame render
  25524. * @param func defines the function to unregister
  25525. */
  25526. Scene.prototype.unregisterAfterRender = function (func) {
  25527. this.onAfterRenderObservable.removeCallback(func);
  25528. };
  25529. Scene.prototype._executeOnceBeforeRender = function (func) {
  25530. var _this = this;
  25531. var execFunc = function () {
  25532. func();
  25533. setTimeout(function () {
  25534. _this.unregisterBeforeRender(execFunc);
  25535. });
  25536. };
  25537. this.registerBeforeRender(execFunc);
  25538. };
  25539. /**
  25540. * The provided function will run before render once and will be disposed afterwards.
  25541. * A timeout delay can be provided so that the function will be executed in N ms.
  25542. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25543. * @param func The function to be executed.
  25544. * @param timeout optional delay in ms
  25545. */
  25546. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25547. var _this = this;
  25548. if (timeout !== undefined) {
  25549. setTimeout(function () {
  25550. _this._executeOnceBeforeRender(func);
  25551. }, timeout);
  25552. }
  25553. else {
  25554. this._executeOnceBeforeRender(func);
  25555. }
  25556. };
  25557. /** @hidden */
  25558. Scene.prototype._addPendingData = function (data) {
  25559. this._pendingData.push(data);
  25560. };
  25561. /** @hidden */
  25562. Scene.prototype._removePendingData = function (data) {
  25563. var wasLoading = this.isLoading;
  25564. var index = this._pendingData.indexOf(data);
  25565. if (index !== -1) {
  25566. this._pendingData.splice(index, 1);
  25567. }
  25568. if (wasLoading && !this.isLoading) {
  25569. this.onDataLoadedObservable.notifyObservers(this);
  25570. }
  25571. };
  25572. /**
  25573. * Returns the number of items waiting to be loaded
  25574. * @returns the number of items waiting to be loaded
  25575. */
  25576. Scene.prototype.getWaitingItemsCount = function () {
  25577. return this._pendingData.length;
  25578. };
  25579. Object.defineProperty(Scene.prototype, "isLoading", {
  25580. /**
  25581. * Returns a boolean indicating if the scene is still loading data
  25582. */
  25583. get: function () {
  25584. return this._pendingData.length > 0;
  25585. },
  25586. enumerable: true,
  25587. configurable: true
  25588. });
  25589. /**
  25590. * Registers a function to be executed when the scene is ready
  25591. * @param {Function} func - the function to be executed
  25592. */
  25593. Scene.prototype.executeWhenReady = function (func) {
  25594. var _this = this;
  25595. this.onReadyObservable.add(func);
  25596. if (this._executeWhenReadyTimeoutId !== -1) {
  25597. return;
  25598. }
  25599. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25600. _this._checkIsReady();
  25601. }, 150);
  25602. };
  25603. /**
  25604. * Returns a promise that resolves when the scene is ready
  25605. * @returns A promise that resolves when the scene is ready
  25606. */
  25607. Scene.prototype.whenReadyAsync = function () {
  25608. var _this = this;
  25609. return new Promise(function (resolve) {
  25610. _this.executeWhenReady(function () {
  25611. resolve();
  25612. });
  25613. });
  25614. };
  25615. /** @hidden */
  25616. Scene.prototype._checkIsReady = function () {
  25617. var _this = this;
  25618. if (this.isReady()) {
  25619. this.onReadyObservable.notifyObservers(this);
  25620. this.onReadyObservable.clear();
  25621. this._executeWhenReadyTimeoutId = -1;
  25622. return;
  25623. }
  25624. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25625. _this._checkIsReady();
  25626. }, 150);
  25627. };
  25628. // Animations
  25629. /**
  25630. * Will start the animation sequence of a given target
  25631. * @param target defines the target
  25632. * @param from defines from which frame should animation start
  25633. * @param to defines until which frame should animation run.
  25634. * @param weight defines the weight to apply to the animation (1.0 by default)
  25635. * @param loop defines if the animation loops
  25636. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25637. * @param onAnimationEnd defines the function to be executed when the animation ends
  25638. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25639. * @returns the animatable object created for this animation
  25640. */
  25641. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25642. if (weight === void 0) { weight = 1.0; }
  25643. if (speedRatio === void 0) { speedRatio = 1.0; }
  25644. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25645. returnedAnimatable.weight = weight;
  25646. return returnedAnimatable;
  25647. };
  25648. /**
  25649. * Will start the animation sequence of a given target
  25650. * @param target defines the target
  25651. * @param from defines from which frame should animation start
  25652. * @param to defines until which frame should animation run.
  25653. * @param loop defines if the animation loops
  25654. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25655. * @param onAnimationEnd defines the function to be executed when the animation ends
  25656. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25657. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25658. * @returns the animatable object created for this animation
  25659. */
  25660. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25661. if (speedRatio === void 0) { speedRatio = 1.0; }
  25662. if (stopCurrent === void 0) { stopCurrent = true; }
  25663. if (from > to && speedRatio > 0) {
  25664. speedRatio *= -1;
  25665. }
  25666. if (stopCurrent) {
  25667. this.stopAnimation(target);
  25668. }
  25669. if (!animatable) {
  25670. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25671. }
  25672. // Local animations
  25673. if (target.animations) {
  25674. animatable.appendAnimations(target, target.animations);
  25675. }
  25676. // Children animations
  25677. if (target.getAnimatables) {
  25678. var animatables = target.getAnimatables();
  25679. for (var index = 0; index < animatables.length; index++) {
  25680. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25681. }
  25682. }
  25683. animatable.reset();
  25684. return animatable;
  25685. };
  25686. /**
  25687. * Begin a new animation on a given node
  25688. * @param target defines the target where the animation will take place
  25689. * @param animations defines the list of animations to start
  25690. * @param from defines the initial value
  25691. * @param to defines the final value
  25692. * @param loop defines if you want animation to loop (off by default)
  25693. * @param speedRatio defines the speed ratio to apply to all animations
  25694. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25695. * @returns the list of created animatables
  25696. */
  25697. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25698. if (speedRatio === undefined) {
  25699. speedRatio = 1.0;
  25700. }
  25701. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25702. return animatable;
  25703. };
  25704. /**
  25705. * Begin a new animation on a given node and its hierarchy
  25706. * @param target defines the root node where the animation will take place
  25707. * @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.
  25708. * @param animations defines the list of animations to start
  25709. * @param from defines the initial value
  25710. * @param to defines the final value
  25711. * @param loop defines if you want animation to loop (off by default)
  25712. * @param speedRatio defines the speed ratio to apply to all animations
  25713. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25714. * @returns the list of animatables created for all nodes
  25715. */
  25716. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25717. var children = target.getDescendants(directDescendantsOnly);
  25718. var result = [];
  25719. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25720. var child = children_1[_i];
  25721. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25722. }
  25723. return result;
  25724. };
  25725. /**
  25726. * Gets the animatable associated with a specific target
  25727. * @param target defines the target of the animatable
  25728. * @returns the required animatable if found
  25729. */
  25730. Scene.prototype.getAnimatableByTarget = function (target) {
  25731. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25732. if (this._activeAnimatables[index].target === target) {
  25733. return this._activeAnimatables[index];
  25734. }
  25735. }
  25736. return null;
  25737. };
  25738. /**
  25739. * Gets all animatables associated with a given target
  25740. * @param target defines the target to look animatables for
  25741. * @returns an array of Animatables
  25742. */
  25743. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25744. var result = [];
  25745. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25746. if (this._activeAnimatables[index].target === target) {
  25747. result.push(this._activeAnimatables[index]);
  25748. }
  25749. }
  25750. return result;
  25751. };
  25752. Object.defineProperty(Scene.prototype, "animatables", {
  25753. /**
  25754. * Gets all animatable attached to the scene
  25755. */
  25756. get: function () {
  25757. return this._activeAnimatables;
  25758. },
  25759. enumerable: true,
  25760. configurable: true
  25761. });
  25762. /**
  25763. * Will stop the animation of the given target
  25764. * @param target - the target
  25765. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25766. */
  25767. Scene.prototype.stopAnimation = function (target, animationName) {
  25768. var animatables = this.getAllAnimatablesByTarget(target);
  25769. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25770. var animatable = animatables_1[_i];
  25771. animatable.stop(animationName);
  25772. }
  25773. };
  25774. /**
  25775. * Stops and removes all animations that have been applied to the scene
  25776. */
  25777. Scene.prototype.stopAllAnimations = function () {
  25778. if (this._activeAnimatables) {
  25779. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25780. this._activeAnimatables[i].stop();
  25781. }
  25782. this._activeAnimatables = [];
  25783. }
  25784. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25785. var group = _a[_i];
  25786. group.stop();
  25787. }
  25788. };
  25789. Scene.prototype._animate = function () {
  25790. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25791. return;
  25792. }
  25793. // Getting time
  25794. var now = BABYLON.Tools.Now;
  25795. if (!this._animationTimeLast) {
  25796. if (this._pendingData.length > 0) {
  25797. return;
  25798. }
  25799. this._animationTimeLast = now;
  25800. }
  25801. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25802. this._animationTime += deltaTime;
  25803. this._animationTimeLast = now;
  25804. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25805. this._activeAnimatables[index]._animate(this._animationTime);
  25806. }
  25807. // Late animation bindings
  25808. this._processLateAnimationBindings();
  25809. };
  25810. /** @hidden */
  25811. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25812. var target = runtimeAnimation.target;
  25813. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25814. if (!target._lateAnimationHolders) {
  25815. target._lateAnimationHolders = {};
  25816. }
  25817. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25818. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25819. totalWeight: 0,
  25820. animations: [],
  25821. originalValue: originalValue
  25822. };
  25823. }
  25824. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25825. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25826. };
  25827. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25828. var normalizer = 1.0;
  25829. var finalPosition = BABYLON.Tmp.Vector3[0];
  25830. var finalScaling = BABYLON.Tmp.Vector3[1];
  25831. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25832. var startIndex = 0;
  25833. var originalAnimation = holder.animations[0];
  25834. var originalValue = holder.originalValue;
  25835. var scale = 1;
  25836. if (holder.totalWeight < 1.0) {
  25837. // We need to mix the original value in
  25838. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25839. scale = 1.0 - holder.totalWeight;
  25840. }
  25841. else {
  25842. startIndex = 1;
  25843. // We need to normalize the weights
  25844. normalizer = holder.totalWeight;
  25845. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25846. scale = originalAnimation.weight / normalizer;
  25847. if (scale == 1) {
  25848. return originalAnimation.currentValue;
  25849. }
  25850. }
  25851. finalScaling.scaleInPlace(scale);
  25852. finalPosition.scaleInPlace(scale);
  25853. finalQuaternion.scaleInPlace(scale);
  25854. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25855. var runtimeAnimation = holder.animations[animIndex];
  25856. var scale = runtimeAnimation.weight / normalizer;
  25857. var currentPosition = BABYLON.Tmp.Vector3[2];
  25858. var currentScaling = BABYLON.Tmp.Vector3[3];
  25859. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25860. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25861. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25862. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25863. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25864. }
  25865. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25866. return originalAnimation._workValue;
  25867. };
  25868. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25869. var originalAnimation = holder.animations[0];
  25870. var originalValue = holder.originalValue;
  25871. if (holder.animations.length === 1) {
  25872. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25873. }
  25874. var normalizer = 1.0;
  25875. var quaternions;
  25876. var weights;
  25877. if (holder.totalWeight < 1.0) {
  25878. var scale = 1.0 - holder.totalWeight;
  25879. quaternions = [];
  25880. weights = [];
  25881. quaternions.push(originalValue);
  25882. weights.push(scale);
  25883. }
  25884. else {
  25885. if (holder.animations.length === 2) { // Slerp as soon as we can
  25886. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  25887. }
  25888. quaternions = [];
  25889. weights = [];
  25890. normalizer = holder.totalWeight;
  25891. }
  25892. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25893. var runtimeAnimation = holder.animations[animIndex];
  25894. quaternions.push(runtimeAnimation.currentValue);
  25895. weights.push(runtimeAnimation.weight / normalizer);
  25896. }
  25897. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  25898. var cumulativeAmount = 0;
  25899. var cumulativeQuaternion = null;
  25900. for (var index = 0; index < quaternions.length;) {
  25901. if (!cumulativeQuaternion) {
  25902. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  25903. cumulativeAmount = weights[index] + weights[index + 1];
  25904. index += 2;
  25905. continue;
  25906. }
  25907. cumulativeAmount += weights[index];
  25908. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  25909. index++;
  25910. }
  25911. return cumulativeQuaternion;
  25912. };
  25913. Scene.prototype._processLateAnimationBindings = function () {
  25914. if (!this._registeredForLateAnimationBindings.length) {
  25915. return;
  25916. }
  25917. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25918. var target = this._registeredForLateAnimationBindings.data[index];
  25919. for (var path in target._lateAnimationHolders) {
  25920. var holder = target._lateAnimationHolders[path];
  25921. var originalAnimation = holder.animations[0];
  25922. var originalValue = holder.originalValue;
  25923. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25924. var finalValue = void 0;
  25925. if (matrixDecomposeMode) {
  25926. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  25927. }
  25928. else {
  25929. var quaternionMode = originalValue.w !== undefined;
  25930. if (quaternionMode) {
  25931. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  25932. }
  25933. else {
  25934. var startIndex = 0;
  25935. var normalizer = 1.0;
  25936. if (holder.totalWeight < 1.0) {
  25937. // We need to mix the original value in
  25938. if (originalValue.scale) {
  25939. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25940. }
  25941. else {
  25942. finalValue = originalValue * (1.0 - holder.totalWeight);
  25943. }
  25944. }
  25945. else {
  25946. // We need to normalize the weights
  25947. normalizer = holder.totalWeight;
  25948. var scale_1 = originalAnimation.weight / normalizer;
  25949. if (scale_1 !== 1) {
  25950. if (originalAnimation.currentValue.scale) {
  25951. finalValue = originalAnimation.currentValue.scale(scale_1);
  25952. }
  25953. else {
  25954. finalValue = originalAnimation.currentValue * scale_1;
  25955. }
  25956. }
  25957. else {
  25958. finalValue = originalAnimation.currentValue;
  25959. }
  25960. startIndex = 1;
  25961. }
  25962. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25963. var runtimeAnimation = holder.animations[animIndex];
  25964. var scale = runtimeAnimation.weight / normalizer;
  25965. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25966. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25967. }
  25968. else {
  25969. finalValue += runtimeAnimation.currentValue * scale;
  25970. }
  25971. }
  25972. }
  25973. }
  25974. target[path] = finalValue;
  25975. }
  25976. target._lateAnimationHolders = {};
  25977. }
  25978. this._registeredForLateAnimationBindings.reset();
  25979. };
  25980. // Matrix
  25981. /** @hidden */
  25982. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25983. this._useAlternateCameraConfiguration = active;
  25984. };
  25985. /**
  25986. * Gets the current view matrix
  25987. * @returns a Matrix
  25988. */
  25989. Scene.prototype.getViewMatrix = function () {
  25990. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25991. };
  25992. /**
  25993. * Gets the current projection matrix
  25994. * @returns a Matrix
  25995. */
  25996. Scene.prototype.getProjectionMatrix = function () {
  25997. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25998. };
  25999. /**
  26000. * Gets the current transform matrix
  26001. * @returns a Matrix made of View * Projection
  26002. */
  26003. Scene.prototype.getTransformMatrix = function () {
  26004. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26005. };
  26006. /**
  26007. * Sets the current transform matrix
  26008. * @param view defines the View matrix to use
  26009. * @param projection defines the Projection matrix to use
  26010. */
  26011. Scene.prototype.setTransformMatrix = function (view, projection) {
  26012. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26013. return;
  26014. }
  26015. this._viewUpdateFlag = view.updateFlag;
  26016. this._projectionUpdateFlag = projection.updateFlag;
  26017. this._viewMatrix = view;
  26018. this._projectionMatrix = projection;
  26019. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26020. // Update frustum
  26021. if (!this._frustumPlanes) {
  26022. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26023. }
  26024. else {
  26025. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26026. }
  26027. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26028. var otherCamera = this.activeCamera._alternateCamera;
  26029. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26030. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26031. }
  26032. if (this._sceneUbo.useUbo) {
  26033. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26034. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26035. this._sceneUbo.update();
  26036. }
  26037. };
  26038. /** @hidden */
  26039. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26040. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26041. return;
  26042. }
  26043. this._alternateViewUpdateFlag = view.updateFlag;
  26044. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26045. this._alternateViewMatrix = view;
  26046. this._alternateProjectionMatrix = projection;
  26047. if (!this._alternateTransformMatrix) {
  26048. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26049. }
  26050. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26051. if (!this._alternateSceneUbo) {
  26052. this._createAlternateUbo();
  26053. }
  26054. if (this._alternateSceneUbo.useUbo) {
  26055. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26056. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26057. this._alternateSceneUbo.update();
  26058. }
  26059. };
  26060. /**
  26061. * Gets the uniform buffer used to store scene data
  26062. * @returns a UniformBuffer
  26063. */
  26064. Scene.prototype.getSceneUniformBuffer = function () {
  26065. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26066. };
  26067. /**
  26068. * Gets an unique (relatively to the current scene) Id
  26069. * @returns an unique number for the scene
  26070. */
  26071. Scene.prototype.getUniqueId = function () {
  26072. var result = Scene._uniqueIdCounter;
  26073. Scene._uniqueIdCounter++;
  26074. return result;
  26075. };
  26076. /**
  26077. * Add a mesh to the list of scene's meshes
  26078. * @param newMesh defines the mesh to add
  26079. */
  26080. Scene.prototype.addMesh = function (newMesh) {
  26081. this.meshes.push(newMesh);
  26082. //notify the collision coordinator
  26083. if (this.collisionCoordinator) {
  26084. this.collisionCoordinator.onMeshAdded(newMesh);
  26085. }
  26086. newMesh._resyncLightSources();
  26087. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26088. };
  26089. /**
  26090. * Remove a mesh for the list of scene's meshes
  26091. * @param toRemove defines the mesh to remove
  26092. * @param recursive if all child meshes should also be removed from the scene
  26093. * @returns the index where the mesh was in the mesh list
  26094. */
  26095. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26096. var _this = this;
  26097. if (recursive === void 0) { recursive = false; }
  26098. var index = this.meshes.indexOf(toRemove);
  26099. if (index !== -1) {
  26100. // Remove from the scene if mesh found
  26101. this.meshes.splice(index, 1);
  26102. }
  26103. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26104. if (recursive) {
  26105. toRemove.getChildMeshes().forEach(function (m) {
  26106. _this.removeMesh(m);
  26107. });
  26108. }
  26109. return index;
  26110. };
  26111. /**
  26112. * Add a transform node to the list of scene's transform nodes
  26113. * @param newTransformNode defines the transform node to add
  26114. */
  26115. Scene.prototype.addTransformNode = function (newTransformNode) {
  26116. this.transformNodes.push(newTransformNode);
  26117. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26118. };
  26119. /**
  26120. * Remove a transform node for the list of scene's transform nodes
  26121. * @param toRemove defines the transform node to remove
  26122. * @returns the index where the transform node was in the transform node list
  26123. */
  26124. Scene.prototype.removeTransformNode = function (toRemove) {
  26125. var index = this.transformNodes.indexOf(toRemove);
  26126. if (index !== -1) {
  26127. // Remove from the scene if found
  26128. this.transformNodes.splice(index, 1);
  26129. }
  26130. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26131. return index;
  26132. };
  26133. /**
  26134. * Remove a skeleton for the list of scene's skeletons
  26135. * @param toRemove defines the skeleton to remove
  26136. * @returns the index where the skeleton was in the skeleton list
  26137. */
  26138. Scene.prototype.removeSkeleton = function (toRemove) {
  26139. var index = this.skeletons.indexOf(toRemove);
  26140. if (index !== -1) {
  26141. // Remove from the scene if found
  26142. this.skeletons.splice(index, 1);
  26143. }
  26144. return index;
  26145. };
  26146. /**
  26147. * Remove a morph target for the list of scene's morph targets
  26148. * @param toRemove defines the morph target to remove
  26149. * @returns the index where the morph target was in the morph target list
  26150. */
  26151. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26152. var index = this.morphTargetManagers.indexOf(toRemove);
  26153. if (index !== -1) {
  26154. // Remove from the scene if found
  26155. this.morphTargetManagers.splice(index, 1);
  26156. }
  26157. return index;
  26158. };
  26159. /**
  26160. * Remove a light for the list of scene's lights
  26161. * @param toRemove defines the light to remove
  26162. * @returns the index where the light was in the light list
  26163. */
  26164. Scene.prototype.removeLight = function (toRemove) {
  26165. var index = this.lights.indexOf(toRemove);
  26166. if (index !== -1) {
  26167. // Remove from meshes
  26168. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26169. var mesh = _a[_i];
  26170. mesh._removeLightSource(toRemove);
  26171. }
  26172. // Remove from the scene if mesh found
  26173. this.lights.splice(index, 1);
  26174. this.sortLightsByPriority();
  26175. }
  26176. this.onLightRemovedObservable.notifyObservers(toRemove);
  26177. return index;
  26178. };
  26179. /**
  26180. * Remove a camera for the list of scene's cameras
  26181. * @param toRemove defines the camera to remove
  26182. * @returns the index where the camera was in the camera list
  26183. */
  26184. Scene.prototype.removeCamera = function (toRemove) {
  26185. var index = this.cameras.indexOf(toRemove);
  26186. if (index !== -1) {
  26187. // Remove from the scene if mesh found
  26188. this.cameras.splice(index, 1);
  26189. }
  26190. // Remove from activeCameras
  26191. var index2 = this.activeCameras.indexOf(toRemove);
  26192. if (index2 !== -1) {
  26193. // Remove from the scene if mesh found
  26194. this.activeCameras.splice(index2, 1);
  26195. }
  26196. // Reset the activeCamera
  26197. if (this.activeCamera === toRemove) {
  26198. if (this.cameras.length > 0) {
  26199. this.activeCamera = this.cameras[0];
  26200. }
  26201. else {
  26202. this.activeCamera = null;
  26203. }
  26204. }
  26205. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26206. return index;
  26207. };
  26208. /**
  26209. * Remove a particle system for the list of scene's particle systems
  26210. * @param toRemove defines the particle system to remove
  26211. * @returns the index where the particle system was in the particle system list
  26212. */
  26213. Scene.prototype.removeParticleSystem = function (toRemove) {
  26214. var index = this.particleSystems.indexOf(toRemove);
  26215. if (index !== -1) {
  26216. this.particleSystems.splice(index, 1);
  26217. }
  26218. return index;
  26219. };
  26220. /**
  26221. * Remove a animation for the list of scene's animations
  26222. * @param toRemove defines the animation to remove
  26223. * @returns the index where the animation was in the animation list
  26224. */
  26225. Scene.prototype.removeAnimation = function (toRemove) {
  26226. var index = this.animations.indexOf(toRemove);
  26227. if (index !== -1) {
  26228. this.animations.splice(index, 1);
  26229. }
  26230. return index;
  26231. };
  26232. /**
  26233. * Removes the given animation group from this scene.
  26234. * @param toRemove The animation group to remove
  26235. * @returns The index of the removed animation group
  26236. */
  26237. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26238. var index = this.animationGroups.indexOf(toRemove);
  26239. if (index !== -1) {
  26240. this.animationGroups.splice(index, 1);
  26241. }
  26242. return index;
  26243. };
  26244. /**
  26245. * Removes the given multi-material from this scene.
  26246. * @param toRemove The multi-material to remove
  26247. * @returns The index of the removed multi-material
  26248. */
  26249. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26250. var index = this.multiMaterials.indexOf(toRemove);
  26251. if (index !== -1) {
  26252. this.multiMaterials.splice(index, 1);
  26253. }
  26254. return index;
  26255. };
  26256. /**
  26257. * Removes the given material from this scene.
  26258. * @param toRemove The material to remove
  26259. * @returns The index of the removed material
  26260. */
  26261. Scene.prototype.removeMaterial = function (toRemove) {
  26262. var index = this.materials.indexOf(toRemove);
  26263. if (index !== -1) {
  26264. this.materials.splice(index, 1);
  26265. }
  26266. return index;
  26267. };
  26268. /**
  26269. * Removes the given lens flare system from this scene.
  26270. * @param toRemove The lens flare system to remove
  26271. * @returns The index of the removed lens flare system
  26272. */
  26273. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26274. var index = this.lensFlareSystems.indexOf(toRemove);
  26275. if (index !== -1) {
  26276. this.lensFlareSystems.splice(index, 1);
  26277. }
  26278. return index;
  26279. };
  26280. /**
  26281. * Removes the given action manager from this scene.
  26282. * @param toRemove The action manager to remove
  26283. * @returns The index of the removed action manager
  26284. */
  26285. Scene.prototype.removeActionManager = function (toRemove) {
  26286. var index = this._actionManagers.indexOf(toRemove);
  26287. if (index !== -1) {
  26288. this._actionManagers.splice(index, 1);
  26289. }
  26290. return index;
  26291. };
  26292. /**
  26293. * Removes the given effect layer from this scene.
  26294. * @param toRemove defines the effect layer to remove
  26295. * @returns the index of the removed effect layer
  26296. */
  26297. Scene.prototype.removeEffectLayer = function (toRemove) {
  26298. var index = this.effectLayers.indexOf(toRemove);
  26299. if (index !== -1) {
  26300. this.effectLayers.splice(index, 1);
  26301. }
  26302. return index;
  26303. };
  26304. /**
  26305. * Removes the given texture from this scene.
  26306. * @param toRemove The texture to remove
  26307. * @returns The index of the removed texture
  26308. */
  26309. Scene.prototype.removeTexture = function (toRemove) {
  26310. var index = this.textures.indexOf(toRemove);
  26311. if (index !== -1) {
  26312. this.textures.splice(index, 1);
  26313. }
  26314. return index;
  26315. };
  26316. /**
  26317. * Adds the given light to this scene
  26318. * @param newLight The light to add
  26319. */
  26320. Scene.prototype.addLight = function (newLight) {
  26321. this.lights.push(newLight);
  26322. this.sortLightsByPriority();
  26323. // Add light to all meshes (To support if the light is removed and then readded)
  26324. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26325. var mesh = _a[_i];
  26326. if (mesh._lightSources.indexOf(newLight) === -1) {
  26327. mesh._lightSources.push(newLight);
  26328. mesh._resyncLightSources();
  26329. }
  26330. }
  26331. this.onNewLightAddedObservable.notifyObservers(newLight);
  26332. };
  26333. /**
  26334. * Sorts the list list based on light priorities
  26335. */
  26336. Scene.prototype.sortLightsByPriority = function () {
  26337. if (this.requireLightSorting) {
  26338. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26339. }
  26340. };
  26341. /**
  26342. * Adds the given camera to this scene
  26343. * @param newCamera The camera to add
  26344. */
  26345. Scene.prototype.addCamera = function (newCamera) {
  26346. this.cameras.push(newCamera);
  26347. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26348. };
  26349. /**
  26350. * Adds the given skeleton to this scene
  26351. * @param newSkeleton The skeleton to add
  26352. */
  26353. Scene.prototype.addSkeleton = function (newSkeleton) {
  26354. this.skeletons.push(newSkeleton);
  26355. };
  26356. /**
  26357. * Adds the given particle system to this scene
  26358. * @param newParticleSystem The particle system to add
  26359. */
  26360. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26361. this.particleSystems.push(newParticleSystem);
  26362. };
  26363. /**
  26364. * Adds the given animation to this scene
  26365. * @param newAnimation The animation to add
  26366. */
  26367. Scene.prototype.addAnimation = function (newAnimation) {
  26368. this.animations.push(newAnimation);
  26369. };
  26370. /**
  26371. * Adds the given animation group to this scene.
  26372. * @param newAnimationGroup The animation group to add
  26373. */
  26374. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26375. this.animationGroups.push(newAnimationGroup);
  26376. };
  26377. /**
  26378. * Adds the given multi-material to this scene
  26379. * @param newMultiMaterial The multi-material to add
  26380. */
  26381. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26382. this.multiMaterials.push(newMultiMaterial);
  26383. };
  26384. /**
  26385. * Adds the given material to this scene
  26386. * @param newMaterial The material to add
  26387. */
  26388. Scene.prototype.addMaterial = function (newMaterial) {
  26389. this.materials.push(newMaterial);
  26390. };
  26391. /**
  26392. * Adds the given morph target to this scene
  26393. * @param newMorphTargetManager The morph target to add
  26394. */
  26395. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26396. this.morphTargetManagers.push(newMorphTargetManager);
  26397. };
  26398. /**
  26399. * Adds the given geometry to this scene
  26400. * @param newGeometry The geometry to add
  26401. */
  26402. Scene.prototype.addGeometry = function (newGeometry) {
  26403. this._geometries.push(newGeometry);
  26404. };
  26405. /**
  26406. * Adds the given lens flare system to this scene
  26407. * @param newLensFlareSystem The lens flare system to add
  26408. */
  26409. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26410. this.lensFlareSystems.push(newLensFlareSystem);
  26411. };
  26412. /**
  26413. * Adds the given effect layer to this scene
  26414. * @param newEffectLayer defines the effect layer to add
  26415. */
  26416. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26417. this.effectLayers.push(newEffectLayer);
  26418. };
  26419. /**
  26420. * Adds the given action manager to this scene
  26421. * @param newActionManager The action manager to add
  26422. */
  26423. Scene.prototype.addActionManager = function (newActionManager) {
  26424. this._actionManagers.push(newActionManager);
  26425. };
  26426. /**
  26427. * Adds the given texture to this scene.
  26428. * @param newTexture The texture to add
  26429. */
  26430. Scene.prototype.addTexture = function (newTexture) {
  26431. this.textures.push(newTexture);
  26432. };
  26433. /**
  26434. * Switch active camera
  26435. * @param newCamera defines the new active camera
  26436. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26437. */
  26438. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26439. if (attachControl === void 0) { attachControl = true; }
  26440. var canvas = this._engine.getRenderingCanvas();
  26441. if (!canvas) {
  26442. return;
  26443. }
  26444. if (this.activeCamera) {
  26445. this.activeCamera.detachControl(canvas);
  26446. }
  26447. this.activeCamera = newCamera;
  26448. if (attachControl) {
  26449. newCamera.attachControl(canvas);
  26450. }
  26451. };
  26452. /**
  26453. * sets the active camera of the scene using its ID
  26454. * @param id defines the camera's ID
  26455. * @return the new active camera or null if none found.
  26456. */
  26457. Scene.prototype.setActiveCameraByID = function (id) {
  26458. var camera = this.getCameraByID(id);
  26459. if (camera) {
  26460. this.activeCamera = camera;
  26461. return camera;
  26462. }
  26463. return null;
  26464. };
  26465. /**
  26466. * sets the active camera of the scene using its name
  26467. * @param name defines the camera's name
  26468. * @returns the new active camera or null if none found.
  26469. */
  26470. Scene.prototype.setActiveCameraByName = function (name) {
  26471. var camera = this.getCameraByName(name);
  26472. if (camera) {
  26473. this.activeCamera = camera;
  26474. return camera;
  26475. }
  26476. return null;
  26477. };
  26478. /**
  26479. * get an animation group using its name
  26480. * @param name defines the material's name
  26481. * @return the animation group or null if none found.
  26482. */
  26483. Scene.prototype.getAnimationGroupByName = function (name) {
  26484. for (var index = 0; index < this.animationGroups.length; index++) {
  26485. if (this.animationGroups[index].name === name) {
  26486. return this.animationGroups[index];
  26487. }
  26488. }
  26489. return null;
  26490. };
  26491. /**
  26492. * get a material using its id
  26493. * @param id defines the material's ID
  26494. * @return the material or null if none found.
  26495. */
  26496. Scene.prototype.getMaterialByID = function (id) {
  26497. for (var index = 0; index < this.materials.length; index++) {
  26498. if (this.materials[index].id === id) {
  26499. return this.materials[index];
  26500. }
  26501. }
  26502. return null;
  26503. };
  26504. /**
  26505. * Gets a material using its name
  26506. * @param name defines the material's name
  26507. * @return the material or null if none found.
  26508. */
  26509. Scene.prototype.getMaterialByName = function (name) {
  26510. for (var index = 0; index < this.materials.length; index++) {
  26511. if (this.materials[index].name === name) {
  26512. return this.materials[index];
  26513. }
  26514. }
  26515. return null;
  26516. };
  26517. /**
  26518. * Gets a lens flare system using its name
  26519. * @param name defines the name to look for
  26520. * @returns the lens flare system or null if not found
  26521. */
  26522. Scene.prototype.getLensFlareSystemByName = function (name) {
  26523. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26524. if (this.lensFlareSystems[index].name === name) {
  26525. return this.lensFlareSystems[index];
  26526. }
  26527. }
  26528. return null;
  26529. };
  26530. /**
  26531. * Gets a lens flare system using its id
  26532. * @param id defines the id to look for
  26533. * @returns the lens flare system or null if not found
  26534. */
  26535. Scene.prototype.getLensFlareSystemByID = function (id) {
  26536. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26537. if (this.lensFlareSystems[index].id === id) {
  26538. return this.lensFlareSystems[index];
  26539. }
  26540. }
  26541. return null;
  26542. };
  26543. /**
  26544. * Gets a camera using its id
  26545. * @param id defines the id to look for
  26546. * @returns the camera or null if not found
  26547. */
  26548. Scene.prototype.getCameraByID = function (id) {
  26549. for (var index = 0; index < this.cameras.length; index++) {
  26550. if (this.cameras[index].id === id) {
  26551. return this.cameras[index];
  26552. }
  26553. }
  26554. return null;
  26555. };
  26556. /**
  26557. * Gets a camera using its unique id
  26558. * @param uniqueId defines the unique id to look for
  26559. * @returns the camera or null if not found
  26560. */
  26561. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26562. for (var index = 0; index < this.cameras.length; index++) {
  26563. if (this.cameras[index].uniqueId === uniqueId) {
  26564. return this.cameras[index];
  26565. }
  26566. }
  26567. return null;
  26568. };
  26569. /**
  26570. * Gets a camera using its name
  26571. * @param name defines the camera's name
  26572. * @return the camera or null if none found.
  26573. */
  26574. Scene.prototype.getCameraByName = function (name) {
  26575. for (var index = 0; index < this.cameras.length; index++) {
  26576. if (this.cameras[index].name === name) {
  26577. return this.cameras[index];
  26578. }
  26579. }
  26580. return null;
  26581. };
  26582. /**
  26583. * Gets a bone using its id
  26584. * @param id defines the bone's id
  26585. * @return the bone or null if not found
  26586. */
  26587. Scene.prototype.getBoneByID = function (id) {
  26588. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26589. var skeleton = this.skeletons[skeletonIndex];
  26590. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26591. if (skeleton.bones[boneIndex].id === id) {
  26592. return skeleton.bones[boneIndex];
  26593. }
  26594. }
  26595. }
  26596. return null;
  26597. };
  26598. /**
  26599. * Gets a bone using its id
  26600. * @param name defines the bone's name
  26601. * @return the bone or null if not found
  26602. */
  26603. Scene.prototype.getBoneByName = function (name) {
  26604. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26605. var skeleton = this.skeletons[skeletonIndex];
  26606. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26607. if (skeleton.bones[boneIndex].name === name) {
  26608. return skeleton.bones[boneIndex];
  26609. }
  26610. }
  26611. }
  26612. return null;
  26613. };
  26614. /**
  26615. * Gets a light node using its name
  26616. * @param name defines the the light's name
  26617. * @return the light or null if none found.
  26618. */
  26619. Scene.prototype.getLightByName = function (name) {
  26620. for (var index = 0; index < this.lights.length; index++) {
  26621. if (this.lights[index].name === name) {
  26622. return this.lights[index];
  26623. }
  26624. }
  26625. return null;
  26626. };
  26627. /**
  26628. * Gets a light node using its id
  26629. * @param id defines the light's id
  26630. * @return the light or null if none found.
  26631. */
  26632. Scene.prototype.getLightByID = function (id) {
  26633. for (var index = 0; index < this.lights.length; index++) {
  26634. if (this.lights[index].id === id) {
  26635. return this.lights[index];
  26636. }
  26637. }
  26638. return null;
  26639. };
  26640. /**
  26641. * Gets a light node using its scene-generated unique ID
  26642. * @param uniqueId defines the light's unique id
  26643. * @return the light or null if none found.
  26644. */
  26645. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26646. for (var index = 0; index < this.lights.length; index++) {
  26647. if (this.lights[index].uniqueId === uniqueId) {
  26648. return this.lights[index];
  26649. }
  26650. }
  26651. return null;
  26652. };
  26653. /**
  26654. * Gets a particle system by id
  26655. * @param id defines the particle system id
  26656. * @return the corresponding system or null if none found
  26657. */
  26658. Scene.prototype.getParticleSystemByID = function (id) {
  26659. for (var index = 0; index < this.particleSystems.length; index++) {
  26660. if (this.particleSystems[index].id === id) {
  26661. return this.particleSystems[index];
  26662. }
  26663. }
  26664. return null;
  26665. };
  26666. /**
  26667. * Gets a geometry using its ID
  26668. * @param id defines the geometry's id
  26669. * @return the geometry or null if none found.
  26670. */
  26671. Scene.prototype.getGeometryByID = function (id) {
  26672. for (var index = 0; index < this._geometries.length; index++) {
  26673. if (this._geometries[index].id === id) {
  26674. return this._geometries[index];
  26675. }
  26676. }
  26677. return null;
  26678. };
  26679. /**
  26680. * Add a new geometry to this scene
  26681. * @param geometry defines the geometry to be added to the scene.
  26682. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26683. * @return a boolean defining if the geometry was added or not
  26684. */
  26685. Scene.prototype.pushGeometry = function (geometry, force) {
  26686. if (!force && this.getGeometryByID(geometry.id)) {
  26687. return false;
  26688. }
  26689. this._geometries.push(geometry);
  26690. //notify the collision coordinator
  26691. if (this.collisionCoordinator) {
  26692. this.collisionCoordinator.onGeometryAdded(geometry);
  26693. }
  26694. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26695. return true;
  26696. };
  26697. /**
  26698. * Removes an existing geometry
  26699. * @param geometry defines the geometry to be removed from the scene
  26700. * @return a boolean defining if the geometry was removed or not
  26701. */
  26702. Scene.prototype.removeGeometry = function (geometry) {
  26703. var index = this._geometries.indexOf(geometry);
  26704. if (index > -1) {
  26705. this._geometries.splice(index, 1);
  26706. //notify the collision coordinator
  26707. if (this.collisionCoordinator) {
  26708. this.collisionCoordinator.onGeometryDeleted(geometry);
  26709. }
  26710. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26711. return true;
  26712. }
  26713. return false;
  26714. };
  26715. /**
  26716. * Gets the list of geometries attached to the scene
  26717. * @returns an array of Geometry
  26718. */
  26719. Scene.prototype.getGeometries = function () {
  26720. return this._geometries;
  26721. };
  26722. /**
  26723. * Gets the first added mesh found of a given ID
  26724. * @param id defines the id to search for
  26725. * @return the mesh found or null if not found at all
  26726. */
  26727. Scene.prototype.getMeshByID = function (id) {
  26728. for (var index = 0; index < this.meshes.length; index++) {
  26729. if (this.meshes[index].id === id) {
  26730. return this.meshes[index];
  26731. }
  26732. }
  26733. return null;
  26734. };
  26735. /**
  26736. * Gets a list of meshes using their id
  26737. * @param id defines the id to search for
  26738. * @returns a list of meshes
  26739. */
  26740. Scene.prototype.getMeshesByID = function (id) {
  26741. return this.meshes.filter(function (m) {
  26742. return m.id === id;
  26743. });
  26744. };
  26745. /**
  26746. * Gets the first added transform node found of a given ID
  26747. * @param id defines the id to search for
  26748. * @return the found transform node or null if not found at all.
  26749. */
  26750. Scene.prototype.getTransformNodeByID = function (id) {
  26751. for (var index = 0; index < this.transformNodes.length; index++) {
  26752. if (this.transformNodes[index].id === id) {
  26753. return this.transformNodes[index];
  26754. }
  26755. }
  26756. return null;
  26757. };
  26758. /**
  26759. * Gets a list of transform nodes using their id
  26760. * @param id defines the id to search for
  26761. * @returns a list of transform nodes
  26762. */
  26763. Scene.prototype.getTransformNodesByID = function (id) {
  26764. return this.transformNodes.filter(function (m) {
  26765. return m.id === id;
  26766. });
  26767. };
  26768. /**
  26769. * Gets a mesh with its auto-generated unique id
  26770. * @param uniqueId defines the unique id to search for
  26771. * @return the found mesh or null if not found at all.
  26772. */
  26773. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26774. for (var index = 0; index < this.meshes.length; index++) {
  26775. if (this.meshes[index].uniqueId === uniqueId) {
  26776. return this.meshes[index];
  26777. }
  26778. }
  26779. return null;
  26780. };
  26781. /**
  26782. * Gets a the last added mesh using a given id
  26783. * @param id defines the id to search for
  26784. * @return the found mesh or null if not found at all.
  26785. */
  26786. Scene.prototype.getLastMeshByID = function (id) {
  26787. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26788. if (this.meshes[index].id === id) {
  26789. return this.meshes[index];
  26790. }
  26791. }
  26792. return null;
  26793. };
  26794. /**
  26795. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26796. * @param id defines the id to search for
  26797. * @return the found node or null if not found at all
  26798. */
  26799. Scene.prototype.getLastEntryByID = function (id) {
  26800. var index;
  26801. for (index = this.meshes.length - 1; index >= 0; index--) {
  26802. if (this.meshes[index].id === id) {
  26803. return this.meshes[index];
  26804. }
  26805. }
  26806. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26807. if (this.transformNodes[index].id === id) {
  26808. return this.transformNodes[index];
  26809. }
  26810. }
  26811. for (index = this.cameras.length - 1; index >= 0; index--) {
  26812. if (this.cameras[index].id === id) {
  26813. return this.cameras[index];
  26814. }
  26815. }
  26816. for (index = this.lights.length - 1; index >= 0; index--) {
  26817. if (this.lights[index].id === id) {
  26818. return this.lights[index];
  26819. }
  26820. }
  26821. return null;
  26822. };
  26823. /**
  26824. * Gets a node (Mesh, Camera, Light) using a given id
  26825. * @param id defines the id to search for
  26826. * @return the found node or null if not found at all
  26827. */
  26828. Scene.prototype.getNodeByID = function (id) {
  26829. var mesh = this.getMeshByID(id);
  26830. if (mesh) {
  26831. return mesh;
  26832. }
  26833. var light = this.getLightByID(id);
  26834. if (light) {
  26835. return light;
  26836. }
  26837. var camera = this.getCameraByID(id);
  26838. if (camera) {
  26839. return camera;
  26840. }
  26841. var bone = this.getBoneByID(id);
  26842. return bone;
  26843. };
  26844. /**
  26845. * Gets a node (Mesh, Camera, Light) using a given name
  26846. * @param name defines the name to search for
  26847. * @return the found node or null if not found at all.
  26848. */
  26849. Scene.prototype.getNodeByName = function (name) {
  26850. var mesh = this.getMeshByName(name);
  26851. if (mesh) {
  26852. return mesh;
  26853. }
  26854. var light = this.getLightByName(name);
  26855. if (light) {
  26856. return light;
  26857. }
  26858. var camera = this.getCameraByName(name);
  26859. if (camera) {
  26860. return camera;
  26861. }
  26862. var bone = this.getBoneByName(name);
  26863. return bone;
  26864. };
  26865. /**
  26866. * Gets a mesh using a given name
  26867. * @param name defines the name to search for
  26868. * @return the found mesh or null if not found at all.
  26869. */
  26870. Scene.prototype.getMeshByName = function (name) {
  26871. for (var index = 0; index < this.meshes.length; index++) {
  26872. if (this.meshes[index].name === name) {
  26873. return this.meshes[index];
  26874. }
  26875. }
  26876. return null;
  26877. };
  26878. /**
  26879. * Gets a transform node using a given name
  26880. * @param name defines the name to search for
  26881. * @return the found transform node or null if not found at all.
  26882. */
  26883. Scene.prototype.getTransformNodeByName = function (name) {
  26884. for (var index = 0; index < this.transformNodes.length; index++) {
  26885. if (this.transformNodes[index].name === name) {
  26886. return this.transformNodes[index];
  26887. }
  26888. }
  26889. return null;
  26890. };
  26891. /**
  26892. * Gets a sound using a given name
  26893. * @param name defines the name to search for
  26894. * @return the found sound or null if not found at all.
  26895. */
  26896. Scene.prototype.getSoundByName = function (name) {
  26897. var index;
  26898. if (BABYLON.AudioEngine) {
  26899. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26900. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26901. return this.mainSoundTrack.soundCollection[index];
  26902. }
  26903. }
  26904. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26905. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26906. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26907. return this.soundTracks[sdIndex].soundCollection[index];
  26908. }
  26909. }
  26910. }
  26911. }
  26912. return null;
  26913. };
  26914. /**
  26915. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26916. * @param id defines the id to search for
  26917. * @return the found skeleton or null if not found at all.
  26918. */
  26919. Scene.prototype.getLastSkeletonByID = function (id) {
  26920. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26921. if (this.skeletons[index].id === id) {
  26922. return this.skeletons[index];
  26923. }
  26924. }
  26925. return null;
  26926. };
  26927. /**
  26928. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26929. * @param id defines the id to search for
  26930. * @return the found skeleton or null if not found at all.
  26931. */
  26932. Scene.prototype.getSkeletonById = function (id) {
  26933. for (var index = 0; index < this.skeletons.length; index++) {
  26934. if (this.skeletons[index].id === id) {
  26935. return this.skeletons[index];
  26936. }
  26937. }
  26938. return null;
  26939. };
  26940. /**
  26941. * Gets a skeleton using a given name
  26942. * @param name defines the name to search for
  26943. * @return the found skeleton or null if not found at all.
  26944. */
  26945. Scene.prototype.getSkeletonByName = function (name) {
  26946. for (var index = 0; index < this.skeletons.length; index++) {
  26947. if (this.skeletons[index].name === name) {
  26948. return this.skeletons[index];
  26949. }
  26950. }
  26951. return null;
  26952. };
  26953. /**
  26954. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26955. * @param id defines the id to search for
  26956. * @return the found morph target manager or null if not found at all.
  26957. */
  26958. Scene.prototype.getMorphTargetManagerById = function (id) {
  26959. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26960. if (this.morphTargetManagers[index].uniqueId === id) {
  26961. return this.morphTargetManagers[index];
  26962. }
  26963. }
  26964. return null;
  26965. };
  26966. /**
  26967. * Gets a boolean indicating if the given mesh is active
  26968. * @param mesh defines the mesh to look for
  26969. * @returns true if the mesh is in the active list
  26970. */
  26971. Scene.prototype.isActiveMesh = function (mesh) {
  26972. return (this._activeMeshes.indexOf(mesh) !== -1);
  26973. };
  26974. /**
  26975. * Return a the first highlight layer of the scene with a given name.
  26976. * @param name The name of the highlight layer to look for.
  26977. * @return The highlight layer if found otherwise null.
  26978. */
  26979. Scene.prototype.getHighlightLayerByName = function (name) {
  26980. for (var index = 0; index < this.effectLayers.length; index++) {
  26981. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26982. return this.effectLayers[index];
  26983. }
  26984. }
  26985. return null;
  26986. };
  26987. /**
  26988. * Return a the first highlight layer of the scene with a given name.
  26989. * @param name The name of the highlight layer to look for.
  26990. * @return The highlight layer if found otherwise null.
  26991. */
  26992. Scene.prototype.getGlowLayerByName = function (name) {
  26993. for (var index = 0; index < this.effectLayers.length; index++) {
  26994. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26995. return this.effectLayers[index];
  26996. }
  26997. }
  26998. return null;
  26999. };
  27000. Object.defineProperty(Scene.prototype, "uid", {
  27001. /**
  27002. * Return a unique id as a string which can serve as an identifier for the scene
  27003. */
  27004. get: function () {
  27005. if (!this._uid) {
  27006. this._uid = BABYLON.Tools.RandomId();
  27007. }
  27008. return this._uid;
  27009. },
  27010. enumerable: true,
  27011. configurable: true
  27012. });
  27013. /**
  27014. * Add an externaly attached data from its key.
  27015. * This method call will fail and return false, if such key already exists.
  27016. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27017. * @param key the unique key that identifies the data
  27018. * @param data the data object to associate to the key for this Engine instance
  27019. * @return true if no such key were already present and the data was added successfully, false otherwise
  27020. */
  27021. Scene.prototype.addExternalData = function (key, data) {
  27022. if (!this._externalData) {
  27023. this._externalData = new BABYLON.StringDictionary();
  27024. }
  27025. return this._externalData.add(key, data);
  27026. };
  27027. /**
  27028. * Get an externaly attached data from its key
  27029. * @param key the unique key that identifies the data
  27030. * @return the associated data, if present (can be null), or undefined if not present
  27031. */
  27032. Scene.prototype.getExternalData = function (key) {
  27033. if (!this._externalData) {
  27034. return null;
  27035. }
  27036. return this._externalData.get(key);
  27037. };
  27038. /**
  27039. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27040. * @param key the unique key that identifies the data
  27041. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27042. * @return the associated data, can be null if the factory returned null.
  27043. */
  27044. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27045. if (!this._externalData) {
  27046. this._externalData = new BABYLON.StringDictionary();
  27047. }
  27048. return this._externalData.getOrAddWithFactory(key, factory);
  27049. };
  27050. /**
  27051. * Remove an externaly attached data from the Engine instance
  27052. * @param key the unique key that identifies the data
  27053. * @return true if the data was successfully removed, false if it doesn't exist
  27054. */
  27055. Scene.prototype.removeExternalData = function (key) {
  27056. return this._externalData.remove(key);
  27057. };
  27058. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27059. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27060. if (mesh.showSubMeshesBoundingBox) {
  27061. var boundingInfo = subMesh.getBoundingInfo();
  27062. if (boundingInfo !== null && boundingInfo !== undefined) {
  27063. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27064. }
  27065. }
  27066. var material = subMesh.getMaterial();
  27067. if (material !== null && material !== undefined) {
  27068. // Render targets
  27069. if (material.getRenderTargetTextures !== undefined) {
  27070. if (this._processedMaterials.indexOf(material) === -1) {
  27071. this._processedMaterials.push(material);
  27072. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27073. }
  27074. }
  27075. // Dispatch
  27076. this._activeIndices.addCount(subMesh.indexCount, false);
  27077. this._renderingManager.dispatch(subMesh, mesh, material);
  27078. }
  27079. }
  27080. };
  27081. /**
  27082. * Clear the processed materials smart array preventing retention point in material dispose.
  27083. */
  27084. Scene.prototype.freeProcessedMaterials = function () {
  27085. this._processedMaterials.dispose();
  27086. };
  27087. /**
  27088. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27089. */
  27090. Scene.prototype.freeActiveMeshes = function () {
  27091. this._activeMeshes.dispose();
  27092. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27093. this.activeCamera._activeMeshes.dispose();
  27094. }
  27095. if (this.activeCameras) {
  27096. for (var i = 0; i < this.activeCameras.length; i++) {
  27097. var activeCamera = this.activeCameras[i];
  27098. if (activeCamera && activeCamera._activeMeshes) {
  27099. activeCamera._activeMeshes.dispose();
  27100. }
  27101. }
  27102. }
  27103. };
  27104. /**
  27105. * Clear the info related to rendering groups preventing retention points during dispose.
  27106. */
  27107. Scene.prototype.freeRenderingGroups = function () {
  27108. if (this._renderingManager) {
  27109. this._renderingManager.freeRenderingGroups();
  27110. }
  27111. if (this.textures) {
  27112. for (var i = 0; i < this.textures.length; i++) {
  27113. var texture = this.textures[i];
  27114. if (texture && texture.renderList) {
  27115. texture.freeRenderingGroups();
  27116. }
  27117. }
  27118. }
  27119. };
  27120. /** @hidden */
  27121. Scene.prototype._isInIntermediateRendering = function () {
  27122. return this._intermediateRendering;
  27123. };
  27124. /**
  27125. * Defines the current active mesh candidate provider
  27126. * @param provider defines the provider to use
  27127. */
  27128. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27129. this._activeMeshCandidateProvider = provider;
  27130. };
  27131. /**
  27132. * Gets the current active mesh candidate provider
  27133. * @returns the current active mesh candidate provider
  27134. */
  27135. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27136. return this._activeMeshCandidateProvider;
  27137. };
  27138. /**
  27139. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27140. * @returns the current scene
  27141. */
  27142. Scene.prototype.freezeActiveMeshes = function () {
  27143. if (!this.activeCamera) {
  27144. return this;
  27145. }
  27146. if (!this._frustumPlanes) {
  27147. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27148. }
  27149. this._evaluateActiveMeshes();
  27150. this._activeMeshesFrozen = true;
  27151. return this;
  27152. };
  27153. /**
  27154. * Use this function to restart evaluating active meshes on every frame
  27155. * @returns the current scene
  27156. */
  27157. Scene.prototype.unfreezeActiveMeshes = function () {
  27158. this._activeMeshesFrozen = false;
  27159. return this;
  27160. };
  27161. Scene.prototype._evaluateActiveMeshes = function () {
  27162. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27163. return;
  27164. }
  27165. if (!this.activeCamera) {
  27166. return;
  27167. }
  27168. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27169. this.activeCamera._activeMeshes.reset();
  27170. this._activeMeshes.reset();
  27171. this._renderingManager.reset();
  27172. this._processedMaterials.reset();
  27173. this._activeParticleSystems.reset();
  27174. this._activeSkeletons.reset();
  27175. this._softwareSkinnedMeshes.reset();
  27176. if (this._boundingBoxRenderer) {
  27177. this._boundingBoxRenderer.reset();
  27178. }
  27179. // Meshes
  27180. var meshes;
  27181. var len;
  27182. var checkIsEnabled = true;
  27183. // Determine mesh candidates
  27184. if (this._activeMeshCandidateProvider !== undefined) {
  27185. // Use _activeMeshCandidateProvider
  27186. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27187. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27188. if (meshes !== undefined) {
  27189. len = meshes.length;
  27190. }
  27191. else {
  27192. len = 0;
  27193. }
  27194. }
  27195. else if (this._selectionOctree !== undefined) {
  27196. // Octree
  27197. var selection = this._selectionOctree.select(this._frustumPlanes);
  27198. meshes = selection.data;
  27199. len = selection.length;
  27200. }
  27201. else {
  27202. // Full scene traversal
  27203. len = this.meshes.length;
  27204. meshes = this.meshes;
  27205. }
  27206. // Check each mesh
  27207. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27208. mesh = meshes[meshIndex];
  27209. if (mesh.isBlocked) {
  27210. continue;
  27211. }
  27212. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27213. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27214. continue;
  27215. }
  27216. mesh.computeWorldMatrix();
  27217. // Intersections
  27218. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27219. this._meshesForIntersections.pushNoDuplicate(mesh);
  27220. }
  27221. // Switch to current LOD
  27222. meshLOD = mesh.getLOD(this.activeCamera);
  27223. if (meshLOD === undefined || meshLOD === null) {
  27224. continue;
  27225. }
  27226. mesh._preActivate();
  27227. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27228. this._activeMeshes.push(mesh);
  27229. this.activeCamera._activeMeshes.push(mesh);
  27230. mesh._activate(this._renderId);
  27231. if (meshLOD !== mesh) {
  27232. meshLOD._activate(this._renderId);
  27233. }
  27234. this._activeMesh(mesh, meshLOD);
  27235. }
  27236. }
  27237. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27238. // Particle systems
  27239. if (this.particlesEnabled) {
  27240. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27241. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27242. var particleSystem = this.particleSystems[particleIndex];
  27243. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27244. continue;
  27245. }
  27246. var emitter = particleSystem.emitter;
  27247. if (!emitter.position || emitter.isEnabled()) {
  27248. this._activeParticleSystems.push(particleSystem);
  27249. particleSystem.animate();
  27250. this._renderingManager.dispatchParticles(particleSystem);
  27251. }
  27252. }
  27253. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27254. }
  27255. };
  27256. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27257. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27258. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27259. mesh.skeleton.prepare();
  27260. }
  27261. if (!mesh.computeBonesUsingShaders) {
  27262. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27263. }
  27264. }
  27265. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27266. var boundingInfo = sourceMesh.getBoundingInfo();
  27267. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27268. }
  27269. if (mesh !== undefined && mesh !== null
  27270. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27271. // Submeshes Octrees
  27272. var len;
  27273. var subMeshes;
  27274. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27275. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27276. len = intersections.length;
  27277. subMeshes = intersections.data;
  27278. }
  27279. else {
  27280. subMeshes = mesh.subMeshes;
  27281. len = subMeshes.length;
  27282. }
  27283. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27284. subMesh = subMeshes[subIndex];
  27285. this._evaluateSubMesh(subMesh, mesh);
  27286. }
  27287. }
  27288. };
  27289. /**
  27290. * Update the transform matrix to update from the current active camera
  27291. * @param force defines a boolean used to force the update even if cache is up to date
  27292. */
  27293. Scene.prototype.updateTransformMatrix = function (force) {
  27294. if (!this.activeCamera) {
  27295. return;
  27296. }
  27297. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27298. };
  27299. /**
  27300. * 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)
  27301. * @param alternateCamera defines the camera to use
  27302. */
  27303. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27304. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27305. };
  27306. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27307. if (camera && camera._skipRendering) {
  27308. return;
  27309. }
  27310. var engine = this._engine;
  27311. this.activeCamera = camera;
  27312. if (!this.activeCamera)
  27313. throw new Error("Active camera not set");
  27314. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27315. // Viewport
  27316. engine.setViewport(this.activeCamera.viewport);
  27317. // Camera
  27318. this.resetCachedMaterial();
  27319. this._renderId++;
  27320. this.updateTransformMatrix();
  27321. if (camera._alternateCamera) {
  27322. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27323. this._alternateRendering = true;
  27324. }
  27325. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27326. // Meshes
  27327. this._evaluateActiveMeshes();
  27328. // Software skinning
  27329. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27330. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27331. mesh.applySkeleton(mesh.skeleton);
  27332. }
  27333. // Render targets
  27334. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27335. var needsRestoreFrameBuffer = false;
  27336. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27337. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27338. }
  27339. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27340. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27341. }
  27342. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27343. this._intermediateRendering = true;
  27344. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27345. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27346. var renderTarget = this._renderTargets.data[renderIndex];
  27347. if (renderTarget._shouldRender()) {
  27348. this._renderId++;
  27349. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27350. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27351. }
  27352. }
  27353. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27354. this._intermediateRendering = false;
  27355. this._renderId++;
  27356. needsRestoreFrameBuffer = true; // Restore back buffer
  27357. }
  27358. // Render EffecttLayer Texture
  27359. var stencilState = this._engine.getStencilBuffer();
  27360. var renderEffects = false;
  27361. var needStencil = false;
  27362. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27363. this._intermediateRendering = true;
  27364. for (var i = 0; i < this.effectLayers.length; i++) {
  27365. var effectLayer = this.effectLayers[i];
  27366. if (effectLayer.shouldRender() &&
  27367. (!effectLayer.camera ||
  27368. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27369. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27370. renderEffects = true;
  27371. needStencil = needStencil || effectLayer.needStencil();
  27372. var renderTarget = effectLayer._mainTexture;
  27373. if (renderTarget._shouldRender()) {
  27374. this._renderId++;
  27375. renderTarget.render(false, false);
  27376. needsRestoreFrameBuffer = true;
  27377. }
  27378. }
  27379. }
  27380. this._intermediateRendering = false;
  27381. this._renderId++;
  27382. }
  27383. if (needsRestoreFrameBuffer) {
  27384. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27385. }
  27386. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27387. // Prepare Frame
  27388. this.postProcessManager._prepareFrame();
  27389. // Backgrounds
  27390. var layerIndex;
  27391. var layer;
  27392. if (this.layers.length) {
  27393. engine.setDepthBuffer(false);
  27394. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27395. layer = this.layers[layerIndex];
  27396. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27397. layer.render();
  27398. }
  27399. }
  27400. engine.setDepthBuffer(true);
  27401. }
  27402. // Activate effect Layer stencil
  27403. if (needStencil) {
  27404. this._engine.setStencilBuffer(true);
  27405. }
  27406. // Render
  27407. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27408. this._renderingManager.render(null, null, true, true);
  27409. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27410. // Restore effect Layer stencil
  27411. if (needStencil) {
  27412. this._engine.setStencilBuffer(stencilState);
  27413. }
  27414. // Bounding boxes
  27415. if (this._boundingBoxRenderer) {
  27416. this._boundingBoxRenderer.render();
  27417. }
  27418. // Lens flares
  27419. if (this.lensFlaresEnabled) {
  27420. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27421. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27422. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27423. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27424. lensFlareSystem.render();
  27425. }
  27426. }
  27427. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27428. }
  27429. // Effect Layer
  27430. if (renderEffects) {
  27431. engine.setDepthBuffer(false);
  27432. for (var i = 0; i < this.effectLayers.length; i++) {
  27433. if (this.effectLayers[i].shouldRender()) {
  27434. this.effectLayers[i].render();
  27435. }
  27436. }
  27437. engine.setDepthBuffer(true);
  27438. }
  27439. // Foregrounds
  27440. if (this.layers.length) {
  27441. engine.setDepthBuffer(false);
  27442. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27443. layer = this.layers[layerIndex];
  27444. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27445. layer.render();
  27446. }
  27447. }
  27448. engine.setDepthBuffer(true);
  27449. }
  27450. // Finalize frame
  27451. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27452. // Reset some special arrays
  27453. this._renderTargets.reset();
  27454. this._alternateRendering = false;
  27455. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27456. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27457. };
  27458. Scene.prototype._processSubCameras = function (camera) {
  27459. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27460. this._renderForCamera(camera);
  27461. return;
  27462. }
  27463. // rig cameras
  27464. for (var index = 0; index < camera._rigCameras.length; index++) {
  27465. this._renderForCamera(camera._rigCameras[index], camera);
  27466. }
  27467. this.activeCamera = camera;
  27468. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27469. };
  27470. Scene.prototype._checkIntersections = function () {
  27471. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27472. var sourceMesh = this._meshesForIntersections.data[index];
  27473. if (!sourceMesh.actionManager) {
  27474. continue;
  27475. }
  27476. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27477. var action = sourceMesh.actionManager.actions[actionIndex];
  27478. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27479. var parameters = action.getTriggerParameter();
  27480. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27481. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27482. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27483. if (areIntersecting && currentIntersectionInProgress === -1) {
  27484. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27485. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27486. sourceMesh._intersectionsInProgress.push(otherMesh);
  27487. }
  27488. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27489. sourceMesh._intersectionsInProgress.push(otherMesh);
  27490. }
  27491. }
  27492. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27493. //They intersected, and now they don't.
  27494. //is this trigger an exit trigger? execute an event.
  27495. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27496. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27497. }
  27498. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27499. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27500. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27501. return otherMesh === parameterMesh;
  27502. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27503. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27504. }
  27505. }
  27506. }
  27507. }
  27508. }
  27509. };
  27510. /**
  27511. * Render the scene
  27512. */
  27513. Scene.prototype.render = function () {
  27514. if (this.isDisposed) {
  27515. return;
  27516. }
  27517. this._activeParticles.fetchNewFrame();
  27518. this._totalVertices.fetchNewFrame();
  27519. this._activeIndices.fetchNewFrame();
  27520. this._activeBones.fetchNewFrame();
  27521. this._meshesForIntersections.reset();
  27522. this.resetCachedMaterial();
  27523. this.onBeforeAnimationsObservable.notifyObservers(this);
  27524. // Actions
  27525. if (this.actionManager) {
  27526. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27527. }
  27528. //Simplification Queue
  27529. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27530. this.simplificationQueue.executeNext();
  27531. }
  27532. if (this._engine.isDeterministicLockStep()) {
  27533. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27534. var defaultFPS = (60.0 / 1000.0);
  27535. var defaultFrameTime = 1000 / 60; // frame time in MS
  27536. if (this._physicsEngine) {
  27537. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27538. }
  27539. var stepsTaken = 0;
  27540. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27541. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27542. internalSteps = Math.min(internalSteps, maxSubSteps);
  27543. do {
  27544. this.onBeforeStepObservable.notifyObservers(this);
  27545. // Animations
  27546. this._animationRatio = defaultFrameTime * defaultFPS;
  27547. this._animate();
  27548. this.onAfterAnimationsObservable.notifyObservers(this);
  27549. // Physics
  27550. if (this._physicsEngine) {
  27551. this.onBeforePhysicsObservable.notifyObservers(this);
  27552. this._physicsEngine._step(defaultFrameTime / 1000);
  27553. this.onAfterPhysicsObservable.notifyObservers(this);
  27554. }
  27555. this.onAfterStepObservable.notifyObservers(this);
  27556. this._currentStepId++;
  27557. stepsTaken++;
  27558. deltaTime -= defaultFrameTime;
  27559. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27560. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27561. }
  27562. else {
  27563. // Animations
  27564. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27565. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27566. this._animate();
  27567. this.onAfterAnimationsObservable.notifyObservers(this);
  27568. // Physics
  27569. if (this._physicsEngine) {
  27570. this.onBeforePhysicsObservable.notifyObservers(this);
  27571. this._physicsEngine._step(deltaTime / 1000.0);
  27572. this.onAfterPhysicsObservable.notifyObservers(this);
  27573. }
  27574. }
  27575. // update gamepad manager
  27576. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27577. this._gamepadManager._checkGamepadsStatus();
  27578. }
  27579. // Update Cameras
  27580. if (this.activeCameras.length > 0) {
  27581. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27582. var camera = this.activeCameras[cameraIndex];
  27583. camera.update();
  27584. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27585. // rig cameras
  27586. for (var index = 0; index < camera._rigCameras.length; index++) {
  27587. camera._rigCameras[index].update();
  27588. }
  27589. }
  27590. }
  27591. }
  27592. else if (this.activeCamera) {
  27593. this.activeCamera.update();
  27594. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27595. // rig cameras
  27596. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27597. this.activeCamera._rigCameras[index].update();
  27598. }
  27599. }
  27600. }
  27601. // Before render
  27602. this.onBeforeRenderObservable.notifyObservers(this);
  27603. // Customs render targets
  27604. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27605. var engine = this.getEngine();
  27606. var currentActiveCamera = this.activeCamera;
  27607. if (this.renderTargetsEnabled) {
  27608. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27609. this._intermediateRendering = true;
  27610. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27611. var renderTarget = this.customRenderTargets[customIndex];
  27612. if (renderTarget._shouldRender()) {
  27613. this._renderId++;
  27614. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27615. if (!this.activeCamera)
  27616. throw new Error("Active camera not set");
  27617. // Viewport
  27618. engine.setViewport(this.activeCamera.viewport);
  27619. // Camera
  27620. this.updateTransformMatrix();
  27621. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27622. }
  27623. }
  27624. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27625. this._intermediateRendering = false;
  27626. this._renderId++;
  27627. }
  27628. // Restore back buffer
  27629. if (this.customRenderTargets.length > 0) {
  27630. engine.restoreDefaultFramebuffer();
  27631. }
  27632. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27633. this.activeCamera = currentActiveCamera;
  27634. // Procedural textures
  27635. if (this.proceduralTexturesEnabled) {
  27636. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27637. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27638. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27639. if (proceduralTexture._shouldRender()) {
  27640. proceduralTexture.render();
  27641. }
  27642. }
  27643. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27644. }
  27645. // Clear
  27646. if (this.autoClearDepthAndStencil || this.autoClear) {
  27647. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27648. }
  27649. // Shadows
  27650. if (this.shadowsEnabled) {
  27651. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27652. var light = this.lights[lightIndex];
  27653. var shadowGenerator = light.getShadowGenerator();
  27654. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27655. var shadowMap = (shadowGenerator.getShadowMap());
  27656. if (this.textures.indexOf(shadowMap) !== -1) {
  27657. this._renderTargets.push(shadowMap);
  27658. }
  27659. }
  27660. }
  27661. }
  27662. // Depth renderer
  27663. for (var key in this._depthRenderer) {
  27664. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27665. }
  27666. // Geometry renderer
  27667. if (this._geometryBufferRenderer) {
  27668. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27669. }
  27670. // RenderPipeline
  27671. if (this._postProcessRenderPipelineManager) {
  27672. this._postProcessRenderPipelineManager.update();
  27673. }
  27674. // Multi-cameras?
  27675. if (this.activeCameras.length > 0) {
  27676. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27677. if (cameraIndex > 0) {
  27678. this._engine.clear(null, false, true, true);
  27679. }
  27680. this._processSubCameras(this.activeCameras[cameraIndex]);
  27681. }
  27682. }
  27683. else {
  27684. if (!this.activeCamera) {
  27685. throw new Error("No camera defined");
  27686. }
  27687. this._processSubCameras(this.activeCamera);
  27688. }
  27689. // Intersection checks
  27690. this._checkIntersections();
  27691. // Update the audio listener attached to the camera
  27692. if (BABYLON.AudioEngine) {
  27693. this._updateAudioParameters();
  27694. }
  27695. // After render
  27696. if (this.afterRender) {
  27697. this.afterRender();
  27698. }
  27699. this.onAfterRenderObservable.notifyObservers(this);
  27700. // Cleaning
  27701. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27702. var data = this._toBeDisposed.data[index];
  27703. if (data) {
  27704. data.dispose();
  27705. }
  27706. this._toBeDisposed[index] = null;
  27707. }
  27708. this._toBeDisposed.reset();
  27709. if (this.dumpNextRenderTargets) {
  27710. this.dumpNextRenderTargets = false;
  27711. }
  27712. this._activeBones.addCount(0, true);
  27713. this._activeIndices.addCount(0, true);
  27714. this._activeParticles.addCount(0, true);
  27715. };
  27716. Scene.prototype._updateAudioParameters = function () {
  27717. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27718. return;
  27719. }
  27720. var listeningCamera;
  27721. var audioEngine = BABYLON.Engine.audioEngine;
  27722. if (this.activeCameras.length > 0) {
  27723. listeningCamera = this.activeCameras[0];
  27724. }
  27725. else {
  27726. listeningCamera = this.activeCamera;
  27727. }
  27728. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27729. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27730. // for VR cameras
  27731. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27732. listeningCamera = listeningCamera.rigCameras[0];
  27733. }
  27734. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27735. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27736. cameraDirection.normalize();
  27737. // To avoid some errors on GearVR
  27738. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27739. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27740. }
  27741. var i;
  27742. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27743. var sound = this.mainSoundTrack.soundCollection[i];
  27744. if (sound.useCustomAttenuation) {
  27745. sound.updateDistanceFromListener();
  27746. }
  27747. }
  27748. for (i = 0; i < this.soundTracks.length; i++) {
  27749. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27750. sound = this.soundTracks[i].soundCollection[j];
  27751. if (sound.useCustomAttenuation) {
  27752. sound.updateDistanceFromListener();
  27753. }
  27754. }
  27755. }
  27756. }
  27757. };
  27758. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27759. // Audio
  27760. /**
  27761. * Gets or sets if audio support is enabled
  27762. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27763. */
  27764. get: function () {
  27765. return this._audioEnabled;
  27766. },
  27767. set: function (value) {
  27768. this._audioEnabled = value;
  27769. if (BABYLON.AudioEngine) {
  27770. if (this._audioEnabled) {
  27771. this._enableAudio();
  27772. }
  27773. else {
  27774. this._disableAudio();
  27775. }
  27776. }
  27777. },
  27778. enumerable: true,
  27779. configurable: true
  27780. });
  27781. Scene.prototype._disableAudio = function () {
  27782. var i;
  27783. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27784. this.mainSoundTrack.soundCollection[i].pause();
  27785. }
  27786. for (i = 0; i < this.soundTracks.length; i++) {
  27787. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27788. this.soundTracks[i].soundCollection[j].pause();
  27789. }
  27790. }
  27791. };
  27792. Scene.prototype._enableAudio = function () {
  27793. var i;
  27794. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27795. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27796. this.mainSoundTrack.soundCollection[i].play();
  27797. }
  27798. }
  27799. for (i = 0; i < this.soundTracks.length; i++) {
  27800. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27801. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27802. this.soundTracks[i].soundCollection[j].play();
  27803. }
  27804. }
  27805. }
  27806. };
  27807. Object.defineProperty(Scene.prototype, "headphone", {
  27808. /**
  27809. * Gets or sets if audio will be output to headphones
  27810. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27811. */
  27812. get: function () {
  27813. return this._headphone;
  27814. },
  27815. set: function (value) {
  27816. this._headphone = value;
  27817. if (BABYLON.AudioEngine) {
  27818. if (this._headphone) {
  27819. this._switchAudioModeForHeadphones();
  27820. }
  27821. else {
  27822. this._switchAudioModeForNormalSpeakers();
  27823. }
  27824. }
  27825. },
  27826. enumerable: true,
  27827. configurable: true
  27828. });
  27829. Scene.prototype._switchAudioModeForHeadphones = function () {
  27830. this.mainSoundTrack.switchPanningModelToHRTF();
  27831. for (var i = 0; i < this.soundTracks.length; i++) {
  27832. this.soundTracks[i].switchPanningModelToHRTF();
  27833. }
  27834. };
  27835. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27836. this.mainSoundTrack.switchPanningModelToEqualPower();
  27837. for (var i = 0; i < this.soundTracks.length; i++) {
  27838. this.soundTracks[i].switchPanningModelToEqualPower();
  27839. }
  27840. };
  27841. /**
  27842. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27843. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27844. * @returns the created depth renderer
  27845. */
  27846. Scene.prototype.enableDepthRenderer = function (camera) {
  27847. camera = camera || this.activeCamera;
  27848. if (!camera) {
  27849. throw "No camera available to enable depth renderer";
  27850. }
  27851. if (!this._depthRenderer[camera.id]) {
  27852. var textureType = 0;
  27853. if (this._engine.getCaps().textureHalfFloatRender) {
  27854. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27855. }
  27856. else if (this._engine.getCaps().textureFloatRender) {
  27857. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27858. }
  27859. else {
  27860. throw "Depth renderer does not support int texture type";
  27861. }
  27862. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27863. }
  27864. return this._depthRenderer[camera.id];
  27865. };
  27866. /**
  27867. * Disables a depth renderer for a given camera
  27868. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27869. */
  27870. Scene.prototype.disableDepthRenderer = function (camera) {
  27871. camera = camera || this.activeCamera;
  27872. if (!camera || !this._depthRenderer[camera.id]) {
  27873. return;
  27874. }
  27875. this._depthRenderer[camera.id].dispose();
  27876. delete this._depthRenderer[camera.id];
  27877. };
  27878. /**
  27879. * Enables a GeometryBufferRender and associates it with the scene
  27880. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27881. * @returns the GeometryBufferRenderer
  27882. */
  27883. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27884. if (ratio === void 0) { ratio = 1; }
  27885. if (this._geometryBufferRenderer) {
  27886. return this._geometryBufferRenderer;
  27887. }
  27888. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27889. if (!this._geometryBufferRenderer.isSupported) {
  27890. this._geometryBufferRenderer = null;
  27891. }
  27892. return this._geometryBufferRenderer;
  27893. };
  27894. /**
  27895. * Disables the GeometryBufferRender associated with the scene
  27896. */
  27897. Scene.prototype.disableGeometryBufferRenderer = function () {
  27898. if (!this._geometryBufferRenderer) {
  27899. return;
  27900. }
  27901. this._geometryBufferRenderer.dispose();
  27902. this._geometryBufferRenderer = null;
  27903. };
  27904. /**
  27905. * Freeze all materials
  27906. * A frozen material will not be updatable but should be faster to render
  27907. */
  27908. Scene.prototype.freezeMaterials = function () {
  27909. for (var i = 0; i < this.materials.length; i++) {
  27910. this.materials[i].freeze();
  27911. }
  27912. };
  27913. /**
  27914. * Unfreeze all materials
  27915. * A frozen material will not be updatable but should be faster to render
  27916. */
  27917. Scene.prototype.unfreezeMaterials = function () {
  27918. for (var i = 0; i < this.materials.length; i++) {
  27919. this.materials[i].unfreeze();
  27920. }
  27921. };
  27922. /**
  27923. * Releases all held ressources
  27924. */
  27925. Scene.prototype.dispose = function () {
  27926. this.beforeRender = null;
  27927. this.afterRender = null;
  27928. this.skeletons = [];
  27929. this.morphTargetManagers = [];
  27930. this.importedMeshesFiles = new Array();
  27931. this.stopAllAnimations();
  27932. this.resetCachedMaterial();
  27933. for (var key in this._depthRenderer) {
  27934. this._depthRenderer[key].dispose();
  27935. }
  27936. if (this._gamepadManager) {
  27937. this._gamepadManager.dispose();
  27938. this._gamepadManager = null;
  27939. }
  27940. // Smart arrays
  27941. if (this.activeCamera) {
  27942. this.activeCamera._activeMeshes.dispose();
  27943. this.activeCamera = null;
  27944. }
  27945. this._activeMeshes.dispose();
  27946. this._renderingManager.dispose();
  27947. this._processedMaterials.dispose();
  27948. this._activeParticleSystems.dispose();
  27949. this._activeSkeletons.dispose();
  27950. this._softwareSkinnedMeshes.dispose();
  27951. this._renderTargets.dispose();
  27952. this._registeredForLateAnimationBindings.dispose();
  27953. if (this._boundingBoxRenderer) {
  27954. this._boundingBoxRenderer.dispose();
  27955. }
  27956. this._meshesForIntersections.dispose();
  27957. this._toBeDisposed.dispose();
  27958. // Abort active requests
  27959. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27960. var request = _a[_i];
  27961. request.abort();
  27962. }
  27963. // Debug layer
  27964. if (this._debugLayer) {
  27965. this._debugLayer.hide();
  27966. }
  27967. // Events
  27968. this.onDisposeObservable.notifyObservers(this);
  27969. this.onDisposeObservable.clear();
  27970. this.onBeforeRenderObservable.clear();
  27971. this.onAfterRenderObservable.clear();
  27972. this.onBeforeRenderTargetsRenderObservable.clear();
  27973. this.onAfterRenderTargetsRenderObservable.clear();
  27974. this.onAfterStepObservable.clear();
  27975. this.onBeforeStepObservable.clear();
  27976. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27977. this.onAfterActiveMeshesEvaluationObservable.clear();
  27978. this.onBeforeParticlesRenderingObservable.clear();
  27979. this.onAfterParticlesRenderingObservable.clear();
  27980. this.onBeforeSpritesRenderingObservable.clear();
  27981. this.onAfterSpritesRenderingObservable.clear();
  27982. this.onBeforeDrawPhaseObservable.clear();
  27983. this.onAfterDrawPhaseObservable.clear();
  27984. this.onBeforePhysicsObservable.clear();
  27985. this.onAfterPhysicsObservable.clear();
  27986. this.onBeforeAnimationsObservable.clear();
  27987. this.onAfterAnimationsObservable.clear();
  27988. this.onDataLoadedObservable.clear();
  27989. this.detachControl();
  27990. // Release sounds & sounds tracks
  27991. if (BABYLON.AudioEngine) {
  27992. this.disposeSounds();
  27993. }
  27994. // VR Helper
  27995. if (this.VRHelper) {
  27996. this.VRHelper.dispose();
  27997. }
  27998. // Detach cameras
  27999. var canvas = this._engine.getRenderingCanvas();
  28000. if (canvas) {
  28001. var index;
  28002. for (index = 0; index < this.cameras.length; index++) {
  28003. this.cameras[index].detachControl(canvas);
  28004. }
  28005. }
  28006. // Release animation groups
  28007. while (this.animationGroups.length) {
  28008. this.animationGroups[0].dispose();
  28009. }
  28010. // Release lights
  28011. while (this.lights.length) {
  28012. this.lights[0].dispose();
  28013. }
  28014. // Release meshes
  28015. while (this.meshes.length) {
  28016. this.meshes[0].dispose(true);
  28017. }
  28018. while (this.transformNodes.length) {
  28019. this.removeTransformNode(this.transformNodes[0]);
  28020. }
  28021. // Release cameras
  28022. while (this.cameras.length) {
  28023. this.cameras[0].dispose();
  28024. }
  28025. // Release materials
  28026. if (this.defaultMaterial) {
  28027. this.defaultMaterial.dispose();
  28028. }
  28029. while (this.multiMaterials.length) {
  28030. this.multiMaterials[0].dispose();
  28031. }
  28032. while (this.materials.length) {
  28033. this.materials[0].dispose();
  28034. }
  28035. // Release particles
  28036. while (this.particleSystems.length) {
  28037. this.particleSystems[0].dispose();
  28038. }
  28039. // Release sprites
  28040. while (this.spriteManagers.length) {
  28041. this.spriteManagers[0].dispose();
  28042. }
  28043. // Release postProcesses
  28044. while (this.postProcesses.length) {
  28045. this.postProcesses[0].dispose();
  28046. }
  28047. // Release layers
  28048. while (this.layers.length) {
  28049. this.layers[0].dispose();
  28050. }
  28051. while (this.effectLayers.length) {
  28052. this.effectLayers[0].dispose();
  28053. }
  28054. // Release textures
  28055. while (this.textures.length) {
  28056. this.textures[0].dispose();
  28057. }
  28058. // Release UBO
  28059. this._sceneUbo.dispose();
  28060. if (this._alternateSceneUbo) {
  28061. this._alternateSceneUbo.dispose();
  28062. }
  28063. // Post-processes
  28064. this.postProcessManager.dispose();
  28065. if (this._postProcessRenderPipelineManager) {
  28066. this._postProcessRenderPipelineManager.dispose();
  28067. }
  28068. // Physics
  28069. if (this._physicsEngine) {
  28070. this.disablePhysicsEngine();
  28071. }
  28072. // Remove from engine
  28073. index = this._engine.scenes.indexOf(this);
  28074. if (index > -1) {
  28075. this._engine.scenes.splice(index, 1);
  28076. }
  28077. this._engine.wipeCaches(true);
  28078. this._isDisposed = true;
  28079. };
  28080. Object.defineProperty(Scene.prototype, "isDisposed", {
  28081. /**
  28082. * Gets if the scene is already disposed
  28083. */
  28084. get: function () {
  28085. return this._isDisposed;
  28086. },
  28087. enumerable: true,
  28088. configurable: true
  28089. });
  28090. /**
  28091. * Releases sounds & soundtracks
  28092. */
  28093. Scene.prototype.disposeSounds = function () {
  28094. if (!this._mainSoundTrack) {
  28095. return;
  28096. }
  28097. this.mainSoundTrack.dispose();
  28098. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28099. this.soundTracks[scIndex].dispose();
  28100. }
  28101. };
  28102. // Octrees
  28103. /**
  28104. * Get the world extend vectors with an optional filter
  28105. *
  28106. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28107. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28108. */
  28109. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28110. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28111. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28112. filterPredicate = filterPredicate || (function () { return true; });
  28113. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28114. mesh.computeWorldMatrix(true);
  28115. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28116. return;
  28117. }
  28118. var boundingInfo = mesh.getBoundingInfo();
  28119. var minBox = boundingInfo.boundingBox.minimumWorld;
  28120. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28121. BABYLON.Tools.CheckExtends(minBox, min, max);
  28122. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28123. });
  28124. return {
  28125. min: min,
  28126. max: max
  28127. };
  28128. };
  28129. /**
  28130. * Creates or updates the octree used to boost selection (picking)
  28131. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28132. * @param maxCapacity defines the maximum capacity per leaf
  28133. * @param maxDepth defines the maximum depth of the octree
  28134. * @returns an octree of AbstractMesh
  28135. */
  28136. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28137. if (maxCapacity === void 0) { maxCapacity = 64; }
  28138. if (maxDepth === void 0) { maxDepth = 2; }
  28139. if (!this._selectionOctree) {
  28140. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28141. }
  28142. var worldExtends = this.getWorldExtends();
  28143. // Update octree
  28144. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28145. return this._selectionOctree;
  28146. };
  28147. // Picking
  28148. /**
  28149. * Creates a ray that can be used to pick in the scene
  28150. * @param x defines the x coordinate of the origin (on-screen)
  28151. * @param y defines the y coordinate of the origin (on-screen)
  28152. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28153. * @param camera defines the camera to use for the picking
  28154. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28155. * @returns a Ray
  28156. */
  28157. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28158. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28159. var result = BABYLON.Ray.Zero();
  28160. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28161. return result;
  28162. };
  28163. /**
  28164. * Creates a ray that can be used to pick in the scene
  28165. * @param x defines the x coordinate of the origin (on-screen)
  28166. * @param y defines the y coordinate of the origin (on-screen)
  28167. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28168. * @param result defines the ray where to store the picking ray
  28169. * @param camera defines the camera to use for the picking
  28170. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28171. * @returns the current scene
  28172. */
  28173. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28174. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28175. var engine = this._engine;
  28176. if (!camera) {
  28177. if (!this.activeCamera)
  28178. throw new Error("Active camera not set");
  28179. camera = this.activeCamera;
  28180. }
  28181. var cameraViewport = camera.viewport;
  28182. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28183. // Moving coordinates to local viewport world
  28184. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28185. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28186. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28187. return this;
  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 camera defines the camera to use for the picking
  28194. * @returns a Ray
  28195. */
  28196. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28197. var result = BABYLON.Ray.Zero();
  28198. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28199. return result;
  28200. };
  28201. /**
  28202. * Creates a ray that can be used to pick in the scene
  28203. * @param x defines the x coordinate of the origin (on-screen)
  28204. * @param y defines the y coordinate of the origin (on-screen)
  28205. * @param result defines the ray where to store the picking ray
  28206. * @param camera defines the camera to use for the picking
  28207. * @returns the current scene
  28208. */
  28209. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28210. if (!BABYLON.PickingInfo) {
  28211. return this;
  28212. }
  28213. var engine = this._engine;
  28214. if (!camera) {
  28215. if (!this.activeCamera)
  28216. throw new Error("Active camera not set");
  28217. camera = this.activeCamera;
  28218. }
  28219. var cameraViewport = camera.viewport;
  28220. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28221. var identity = BABYLON.Matrix.Identity();
  28222. // Moving coordinates to local viewport world
  28223. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28224. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28225. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28226. return this;
  28227. };
  28228. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28229. if (!BABYLON.PickingInfo) {
  28230. return null;
  28231. }
  28232. var pickingInfo = null;
  28233. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28234. var mesh = this.meshes[meshIndex];
  28235. if (predicate) {
  28236. if (!predicate(mesh)) {
  28237. continue;
  28238. }
  28239. }
  28240. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28241. continue;
  28242. }
  28243. var world = mesh.getWorldMatrix();
  28244. var ray = rayFunction(world);
  28245. var result = mesh.intersects(ray, fastCheck);
  28246. if (!result || !result.hit)
  28247. continue;
  28248. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28249. continue;
  28250. pickingInfo = result;
  28251. if (fastCheck) {
  28252. break;
  28253. }
  28254. }
  28255. return pickingInfo || new BABYLON.PickingInfo();
  28256. };
  28257. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28258. if (!BABYLON.PickingInfo) {
  28259. return null;
  28260. }
  28261. var pickingInfos = new Array();
  28262. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28263. var mesh = this.meshes[meshIndex];
  28264. if (predicate) {
  28265. if (!predicate(mesh)) {
  28266. continue;
  28267. }
  28268. }
  28269. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28270. continue;
  28271. }
  28272. var world = mesh.getWorldMatrix();
  28273. var ray = rayFunction(world);
  28274. var result = mesh.intersects(ray, false);
  28275. if (!result || !result.hit)
  28276. continue;
  28277. pickingInfos.push(result);
  28278. }
  28279. return pickingInfos;
  28280. };
  28281. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28282. if (!BABYLON.PickingInfo) {
  28283. return null;
  28284. }
  28285. var pickingInfo = null;
  28286. if (!camera) {
  28287. if (!this.activeCamera) {
  28288. return null;
  28289. }
  28290. camera = this.activeCamera;
  28291. }
  28292. if (this.spriteManagers.length > 0) {
  28293. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28294. var spriteManager = this.spriteManagers[spriteIndex];
  28295. if (!spriteManager.isPickable) {
  28296. continue;
  28297. }
  28298. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28299. if (!result || !result.hit)
  28300. continue;
  28301. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28302. continue;
  28303. pickingInfo = result;
  28304. if (fastCheck) {
  28305. break;
  28306. }
  28307. }
  28308. }
  28309. return pickingInfo || new BABYLON.PickingInfo();
  28310. };
  28311. /** Launch a ray to try to pick a mesh in the scene
  28312. * @param x position on screen
  28313. * @param y position on screen
  28314. * @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
  28315. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28316. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28317. * @returns a PickingInfo
  28318. */
  28319. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28320. var _this = this;
  28321. if (!BABYLON.PickingInfo) {
  28322. return null;
  28323. }
  28324. return this._internalPick(function (world) {
  28325. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28326. return _this._tempPickingRay;
  28327. }, predicate, fastCheck);
  28328. };
  28329. /** Launch a ray to try to pick a sprite in the scene
  28330. * @param x position on screen
  28331. * @param y position on screen
  28332. * @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
  28333. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28334. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28335. * @returns a PickingInfo
  28336. */
  28337. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28338. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28339. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28340. };
  28341. /** Use the given ray to pick a mesh in the scene
  28342. * @param ray The ray to use to pick meshes
  28343. * @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
  28344. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28345. * @returns a PickingInfo
  28346. */
  28347. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28348. var _this = this;
  28349. return this._internalPick(function (world) {
  28350. if (!_this._pickWithRayInverseMatrix) {
  28351. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28352. }
  28353. world.invertToRef(_this._pickWithRayInverseMatrix);
  28354. if (!_this._cachedRayForTransform) {
  28355. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28356. }
  28357. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28358. return _this._cachedRayForTransform;
  28359. }, predicate, fastCheck);
  28360. };
  28361. /**
  28362. * Launch a ray to try to pick a mesh in the scene
  28363. * @param x X position on screen
  28364. * @param y Y position on screen
  28365. * @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
  28366. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28367. * @returns an array of PickingInfo
  28368. */
  28369. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28370. var _this = this;
  28371. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28372. };
  28373. /**
  28374. * Launch a ray to try to pick a mesh in the scene
  28375. * @param ray Ray to use
  28376. * @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
  28377. * @returns an array of PickingInfo
  28378. */
  28379. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28380. var _this = this;
  28381. return this._internalMultiPick(function (world) {
  28382. if (!_this._pickWithRayInverseMatrix) {
  28383. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28384. }
  28385. world.invertToRef(_this._pickWithRayInverseMatrix);
  28386. if (!_this._cachedRayForTransform) {
  28387. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28388. }
  28389. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28390. return _this._cachedRayForTransform;
  28391. }, predicate);
  28392. };
  28393. /**
  28394. * Force the value of meshUnderPointer
  28395. * @param mesh defines the mesh to use
  28396. */
  28397. Scene.prototype.setPointerOverMesh = function (mesh) {
  28398. if (this._pointerOverMesh === mesh) {
  28399. return;
  28400. }
  28401. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28402. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28403. }
  28404. this._pointerOverMesh = mesh;
  28405. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28406. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28407. }
  28408. };
  28409. /**
  28410. * Gets the mesh under the pointer
  28411. * @returns a Mesh or null if no mesh is under the pointer
  28412. */
  28413. Scene.prototype.getPointerOverMesh = function () {
  28414. return this._pointerOverMesh;
  28415. };
  28416. /**
  28417. * Force the sprite under the pointer
  28418. * @param sprite defines the sprite to use
  28419. */
  28420. Scene.prototype.setPointerOverSprite = function (sprite) {
  28421. if (this._pointerOverSprite === sprite) {
  28422. return;
  28423. }
  28424. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28425. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28426. }
  28427. this._pointerOverSprite = sprite;
  28428. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28429. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28430. }
  28431. };
  28432. /**
  28433. * Gets the sprite under the pointer
  28434. * @returns a Sprite or null if no sprite is under the pointer
  28435. */
  28436. Scene.prototype.getPointerOverSprite = function () {
  28437. return this._pointerOverSprite;
  28438. };
  28439. // Physics
  28440. /**
  28441. * Gets the current physics engine
  28442. * @returns a PhysicsEngine or null if none attached
  28443. */
  28444. Scene.prototype.getPhysicsEngine = function () {
  28445. return this._physicsEngine;
  28446. };
  28447. /**
  28448. * Enables physics to the current scene
  28449. * @param gravity defines the scene's gravity for the physics engine
  28450. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28451. * @return a boolean indicating if the physics engine was initialized
  28452. */
  28453. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28454. if (gravity === void 0) { gravity = null; }
  28455. if (this._physicsEngine) {
  28456. return true;
  28457. }
  28458. try {
  28459. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28460. return true;
  28461. }
  28462. catch (e) {
  28463. BABYLON.Tools.Error(e.message);
  28464. return false;
  28465. }
  28466. };
  28467. /**
  28468. * Disables and disposes the physics engine associated with the scene
  28469. */
  28470. Scene.prototype.disablePhysicsEngine = function () {
  28471. if (!this._physicsEngine) {
  28472. return;
  28473. }
  28474. this._physicsEngine.dispose();
  28475. this._physicsEngine = null;
  28476. };
  28477. /**
  28478. * Gets a boolean indicating if there is an active physics engine
  28479. * @returns a boolean indicating if there is an active physics engine
  28480. */
  28481. Scene.prototype.isPhysicsEnabled = function () {
  28482. return this._physicsEngine !== undefined;
  28483. };
  28484. /**
  28485. * Deletes a physics compound impostor
  28486. * @param compound defines the compound to delete
  28487. */
  28488. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28489. var mesh = compound.parts[0].mesh;
  28490. if (mesh.physicsImpostor) {
  28491. mesh.physicsImpostor.dispose( /*true*/);
  28492. mesh.physicsImpostor = null;
  28493. }
  28494. };
  28495. // Misc.
  28496. /** @hidden */
  28497. Scene.prototype._rebuildGeometries = function () {
  28498. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28499. var geometry = _a[_i];
  28500. geometry._rebuild();
  28501. }
  28502. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28503. var mesh = _c[_b];
  28504. mesh._rebuild();
  28505. }
  28506. if (this.postProcessManager) {
  28507. this.postProcessManager._rebuild();
  28508. }
  28509. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28510. var layer = _e[_d];
  28511. layer._rebuild();
  28512. }
  28513. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28514. var effectLayer = _g[_f];
  28515. effectLayer._rebuild();
  28516. }
  28517. if (this._boundingBoxRenderer) {
  28518. this._boundingBoxRenderer._rebuild();
  28519. }
  28520. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28521. var system = _j[_h];
  28522. system.rebuild();
  28523. }
  28524. if (this._postProcessRenderPipelineManager) {
  28525. this._postProcessRenderPipelineManager._rebuild();
  28526. }
  28527. };
  28528. /** @hidden */
  28529. Scene.prototype._rebuildTextures = function () {
  28530. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28531. var texture = _a[_i];
  28532. texture._rebuild();
  28533. }
  28534. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28535. };
  28536. /**
  28537. * Creates a default light for the scene.
  28538. * @param replace Whether to replace the existing lights in the scene.
  28539. */
  28540. Scene.prototype.createDefaultLight = function (replace) {
  28541. if (replace === void 0) { replace = false; }
  28542. // Dispose existing light in replace mode.
  28543. if (replace) {
  28544. if (this.lights) {
  28545. for (var i = 0; i < this.lights.length; i++) {
  28546. this.lights[i].dispose();
  28547. }
  28548. }
  28549. }
  28550. // Light
  28551. if (this.lights.length === 0) {
  28552. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28553. }
  28554. };
  28555. /**
  28556. * Creates a default camera for the scene.
  28557. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28558. * @param replace Whether to replace the existing active camera in the scene.
  28559. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28560. */
  28561. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28562. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28563. if (replace === void 0) { replace = false; }
  28564. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28565. // Dispose existing camera in replace mode.
  28566. if (replace) {
  28567. if (this.activeCamera) {
  28568. this.activeCamera.dispose();
  28569. this.activeCamera = null;
  28570. }
  28571. }
  28572. // Camera
  28573. if (!this.activeCamera) {
  28574. var worldExtends = this.getWorldExtends();
  28575. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28576. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28577. var camera;
  28578. var radius = worldSize.length() * 1.5;
  28579. // empty scene scenario!
  28580. if (!isFinite(radius)) {
  28581. radius = 1;
  28582. worldCenter.copyFromFloats(0, 0, 0);
  28583. }
  28584. if (createArcRotateCamera) {
  28585. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28586. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28587. arcRotateCamera.wheelPrecision = 100 / radius;
  28588. camera = arcRotateCamera;
  28589. }
  28590. else {
  28591. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28592. freeCamera.setTarget(worldCenter);
  28593. camera = freeCamera;
  28594. }
  28595. camera.minZ = radius * 0.01;
  28596. camera.maxZ = radius * 1000;
  28597. camera.speed = radius * 0.2;
  28598. this.activeCamera = camera;
  28599. var canvas = this.getEngine().getRenderingCanvas();
  28600. if (attachCameraControls && canvas) {
  28601. camera.attachControl(canvas);
  28602. }
  28603. }
  28604. };
  28605. /**
  28606. * Creates a default camera and a default light
  28607. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28608. * @param replace defines if the camera and/or light will replace the existing ones
  28609. * @param attachCameraControls defines if attachControl will be called on the new camera
  28610. */
  28611. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28612. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28613. if (replace === void 0) { replace = false; }
  28614. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28615. this.createDefaultLight(replace);
  28616. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28617. };
  28618. /**
  28619. * Creates a new sky box
  28620. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28621. * @param environmentTexture defines the texture to use as environment texture
  28622. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28623. * @param scale defines the overall scale of the skybox
  28624. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28625. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28626. * @returns a new mesh holding the sky box
  28627. */
  28628. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28629. if (pbr === void 0) { pbr = false; }
  28630. if (scale === void 0) { scale = 1000; }
  28631. if (blur === void 0) { blur = 0; }
  28632. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28633. if (!environmentTexture) {
  28634. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28635. return null;
  28636. }
  28637. if (setGlobalEnvTexture) {
  28638. if (environmentTexture) {
  28639. this.environmentTexture = environmentTexture;
  28640. }
  28641. }
  28642. // Skybox
  28643. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28644. if (pbr) {
  28645. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28646. hdrSkyboxMaterial.backFaceCulling = false;
  28647. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28648. if (hdrSkyboxMaterial.reflectionTexture) {
  28649. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28650. }
  28651. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28652. hdrSkyboxMaterial.disableLighting = true;
  28653. hdrSkyboxMaterial.twoSidedLighting = true;
  28654. hdrSkybox.infiniteDistance = true;
  28655. hdrSkybox.material = hdrSkyboxMaterial;
  28656. }
  28657. else {
  28658. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28659. skyboxMaterial.backFaceCulling = false;
  28660. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28661. if (skyboxMaterial.reflectionTexture) {
  28662. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28663. }
  28664. skyboxMaterial.disableLighting = true;
  28665. hdrSkybox.infiniteDistance = true;
  28666. hdrSkybox.material = skyboxMaterial;
  28667. }
  28668. return hdrSkybox;
  28669. };
  28670. /**
  28671. * Creates a new environment
  28672. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28673. * @param options defines the options you can use to configure the environment
  28674. * @returns the new EnvironmentHelper
  28675. */
  28676. Scene.prototype.createDefaultEnvironment = function (options) {
  28677. if (BABYLON.EnvironmentHelper) {
  28678. return new BABYLON.EnvironmentHelper(options, this);
  28679. }
  28680. return null;
  28681. };
  28682. /**
  28683. * Creates a new VREXperienceHelper
  28684. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28685. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28686. * @returns a new VREXperienceHelper
  28687. */
  28688. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28689. if (webVROptions === void 0) { webVROptions = {}; }
  28690. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28691. };
  28692. // Tags
  28693. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28694. if (tagsQuery === undefined) {
  28695. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28696. return list;
  28697. }
  28698. var listByTags = [];
  28699. forEach = forEach || (function (item) { return; });
  28700. for (var i in list) {
  28701. var item = list[i];
  28702. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28703. listByTags.push(item);
  28704. forEach(item);
  28705. }
  28706. }
  28707. return listByTags;
  28708. };
  28709. /**
  28710. * Get a list of meshes by tags
  28711. * @param tagsQuery defines the tags query to use
  28712. * @param forEach defines a predicate used to filter results
  28713. * @returns an array of Mesh
  28714. */
  28715. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28716. return this._getByTags(this.meshes, tagsQuery, forEach);
  28717. };
  28718. /**
  28719. * Get a list of cameras by tags
  28720. * @param tagsQuery defines the tags query to use
  28721. * @param forEach defines a predicate used to filter results
  28722. * @returns an array of Camera
  28723. */
  28724. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28725. return this._getByTags(this.cameras, tagsQuery, forEach);
  28726. };
  28727. /**
  28728. * Get a list of lights by tags
  28729. * @param tagsQuery defines the tags query to use
  28730. * @param forEach defines a predicate used to filter results
  28731. * @returns an array of Light
  28732. */
  28733. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28734. return this._getByTags(this.lights, tagsQuery, forEach);
  28735. };
  28736. /**
  28737. * Get a list of materials by tags
  28738. * @param tagsQuery defines the tags query to use
  28739. * @param forEach defines a predicate used to filter results
  28740. * @returns an array of Material
  28741. */
  28742. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28743. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28744. };
  28745. /**
  28746. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28747. * This allowed control for front to back rendering or reversly depending of the special needs.
  28748. *
  28749. * @param renderingGroupId The rendering group id corresponding to its index
  28750. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28751. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28752. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28753. */
  28754. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28755. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28756. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28757. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28758. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28759. };
  28760. /**
  28761. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28762. *
  28763. * @param renderingGroupId The rendering group id corresponding to its index
  28764. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28765. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28766. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28767. */
  28768. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28769. if (depth === void 0) { depth = true; }
  28770. if (stencil === void 0) { stencil = true; }
  28771. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28772. };
  28773. /**
  28774. * Will flag all materials as dirty to trigger new shader compilation
  28775. * @param flag defines the flag used to specify which material part must be marked as dirty
  28776. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28777. */
  28778. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28779. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28780. var material = _a[_i];
  28781. if (predicate && !predicate(material)) {
  28782. continue;
  28783. }
  28784. material.markAsDirty(flag);
  28785. }
  28786. };
  28787. /** @hidden */
  28788. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28789. var _this = this;
  28790. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28791. this._activeRequests.push(request);
  28792. request.onCompleteObservable.add(function (request) {
  28793. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28794. });
  28795. return request;
  28796. };
  28797. /** @hidden */
  28798. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28799. var _this = this;
  28800. return new Promise(function (resolve, reject) {
  28801. _this._loadFile(url, function (data) {
  28802. resolve(data);
  28803. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28804. reject(exception);
  28805. });
  28806. });
  28807. };
  28808. // Statics
  28809. Scene._FOGMODE_NONE = 0;
  28810. Scene._FOGMODE_EXP = 1;
  28811. Scene._FOGMODE_EXP2 = 2;
  28812. Scene._FOGMODE_LINEAR = 3;
  28813. Scene._uniqueIdCounter = 0;
  28814. /**
  28815. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28816. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28817. */
  28818. Scene.MinDeltaTime = 1.0;
  28819. /**
  28820. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28821. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28822. */
  28823. Scene.MaxDeltaTime = 1000.0;
  28824. /** The distance in pixel that you have to move to prevent some events */
  28825. Scene.DragMovementThreshold = 10; // in pixels
  28826. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28827. Scene.LongPressDelay = 500; // in milliseconds
  28828. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28829. Scene.DoubleClickDelay = 300; // in milliseconds
  28830. /** If you need to check double click without raising a single click at first click, enable this flag */
  28831. Scene.ExclusiveDoubleClickMode = false;
  28832. return Scene;
  28833. }());
  28834. BABYLON.Scene = Scene;
  28835. })(BABYLON || (BABYLON = {}));
  28836. //# sourceMappingURL=babylon.scene.js.map
  28837. var BABYLON;
  28838. (function (BABYLON) {
  28839. /**
  28840. * Set of assets to keep when moving a scene into an asset container.
  28841. */
  28842. var KeepAssets = /** @class */ (function () {
  28843. function KeepAssets() {
  28844. /**
  28845. * Cameras to keep.
  28846. */
  28847. this.cameras = new Array();
  28848. /**
  28849. * Lights to keep.
  28850. */
  28851. this.lights = new Array();
  28852. /**
  28853. * Meshes to keep.
  28854. */
  28855. this.meshes = new Array();
  28856. /**
  28857. * Skeletons to keep.
  28858. */
  28859. this.skeletons = new Array();
  28860. /**
  28861. * ParticleSystems to keep.
  28862. */
  28863. this.particleSystems = new Array();
  28864. /**
  28865. * Animations to keep.
  28866. */
  28867. this.animations = new Array();
  28868. /**
  28869. * AnimationGroups to keep.
  28870. */
  28871. this.animationGroups = new Array();
  28872. /**
  28873. * MultiMaterials to keep.
  28874. */
  28875. this.multiMaterials = new Array();
  28876. /**
  28877. * Materials to keep.
  28878. */
  28879. this.materials = new Array();
  28880. /**
  28881. * MorphTargetManagers to keep.
  28882. */
  28883. this.morphTargetManagers = new Array();
  28884. /**
  28885. * Geometries to keep.
  28886. */
  28887. this.geometries = new Array();
  28888. /**
  28889. * TransformNodes to keep.
  28890. */
  28891. this.transformNodes = new Array();
  28892. /**
  28893. * LensFlareSystems to keep.
  28894. */
  28895. this.lensFlareSystems = new Array();
  28896. /**
  28897. * ShadowGenerators to keep.
  28898. */
  28899. this.shadowGenerators = new Array();
  28900. /**
  28901. * ActionManagers to keep.
  28902. */
  28903. this.actionManagers = new Array();
  28904. /**
  28905. * Sounds to keep.
  28906. */
  28907. this.sounds = new Array();
  28908. /**
  28909. * Textures to keep.
  28910. */
  28911. this.textures = new Array();
  28912. /**
  28913. * Effect layers to keep.
  28914. */
  28915. this.effectLayers = new Array();
  28916. }
  28917. return KeepAssets;
  28918. }());
  28919. BABYLON.KeepAssets = KeepAssets;
  28920. /**
  28921. * Container with a set of assets that can be added or removed from a scene.
  28922. */
  28923. var AssetContainer = /** @class */ (function () {
  28924. /**
  28925. * Instantiates an AssetContainer.
  28926. * @param scene The scene the AssetContainer belongs to.
  28927. */
  28928. function AssetContainer(scene) {
  28929. // Objects
  28930. /**
  28931. * Cameras populated in the container.
  28932. */
  28933. this.cameras = new Array();
  28934. /**
  28935. * Lights populated in the container.
  28936. */
  28937. this.lights = new Array();
  28938. /**
  28939. * Meshes populated in the container.
  28940. */
  28941. this.meshes = new Array();
  28942. /**
  28943. * Skeletons populated in the container.
  28944. */
  28945. this.skeletons = new Array();
  28946. /**
  28947. * ParticleSystems populated in the container.
  28948. */
  28949. this.particleSystems = new Array();
  28950. /**
  28951. * Animations populated in the container.
  28952. */
  28953. this.animations = new Array();
  28954. /**
  28955. * AnimationGroups populated in the container.
  28956. */
  28957. this.animationGroups = new Array();
  28958. /**
  28959. * MultiMaterials populated in the container.
  28960. */
  28961. this.multiMaterials = new Array();
  28962. /**
  28963. * Materials populated in the container.
  28964. */
  28965. this.materials = new Array();
  28966. /**
  28967. * MorphTargetManagers populated in the container.
  28968. */
  28969. this.morphTargetManagers = new Array();
  28970. /**
  28971. * Geometries populated in the container.
  28972. */
  28973. this.geometries = new Array();
  28974. /**
  28975. * TransformNodes populated in the container.
  28976. */
  28977. this.transformNodes = new Array();
  28978. /**
  28979. * LensFlareSystems populated in the container.
  28980. */
  28981. this.lensFlareSystems = new Array();
  28982. /**
  28983. * ShadowGenerators populated in the container.
  28984. */
  28985. this.shadowGenerators = new Array();
  28986. /**
  28987. * ActionManagers populated in the container.
  28988. */
  28989. this.actionManagers = new Array();
  28990. /**
  28991. * Sounds populated in the container.
  28992. */
  28993. this.sounds = new Array();
  28994. /**
  28995. * Textures populated in the container.
  28996. */
  28997. this.textures = new Array();
  28998. /**
  28999. * Effect layers populated in the container.
  29000. */
  29001. this.effectLayers = new Array();
  29002. this.scene = scene;
  29003. }
  29004. /**
  29005. * Adds all the assets from the container to the scene.
  29006. */
  29007. AssetContainer.prototype.addAllToScene = function () {
  29008. var _this = this;
  29009. this.cameras.forEach(function (o) {
  29010. _this.scene.addCamera(o);
  29011. });
  29012. this.lights.forEach(function (o) {
  29013. _this.scene.addLight(o);
  29014. });
  29015. this.meshes.forEach(function (o) {
  29016. _this.scene.addMesh(o);
  29017. });
  29018. this.skeletons.forEach(function (o) {
  29019. _this.scene.addSkeleton(o);
  29020. });
  29021. this.particleSystems.forEach(function (o) {
  29022. _this.scene.addParticleSystem(o);
  29023. });
  29024. this.animations.forEach(function (o) {
  29025. _this.scene.addAnimation(o);
  29026. });
  29027. this.animationGroups.forEach(function (o) {
  29028. _this.scene.addAnimationGroup(o);
  29029. });
  29030. this.multiMaterials.forEach(function (o) {
  29031. _this.scene.addMultiMaterial(o);
  29032. });
  29033. this.materials.forEach(function (o) {
  29034. _this.scene.addMaterial(o);
  29035. });
  29036. this.morphTargetManagers.forEach(function (o) {
  29037. _this.scene.addMorphTargetManager(o);
  29038. });
  29039. this.geometries.forEach(function (o) {
  29040. _this.scene.addGeometry(o);
  29041. });
  29042. this.transformNodes.forEach(function (o) {
  29043. _this.scene.addTransformNode(o);
  29044. });
  29045. this.lensFlareSystems.forEach(function (o) {
  29046. _this.scene.addLensFlareSystem(o);
  29047. });
  29048. this.actionManagers.forEach(function (o) {
  29049. _this.scene.addActionManager(o);
  29050. });
  29051. this.sounds.forEach(function (o) {
  29052. o.play();
  29053. o.autoplay = true;
  29054. _this.scene.mainSoundTrack.AddSound(o);
  29055. });
  29056. this.textures.forEach(function (o) {
  29057. _this.scene.addTexture(o);
  29058. });
  29059. this.effectLayers.forEach(function (o) {
  29060. _this.scene.addEffectLayer(o);
  29061. });
  29062. };
  29063. /**
  29064. * Removes all the assets in the container from the scene
  29065. */
  29066. AssetContainer.prototype.removeAllFromScene = function () {
  29067. var _this = this;
  29068. this.cameras.forEach(function (o) {
  29069. _this.scene.removeCamera(o);
  29070. });
  29071. this.lights.forEach(function (o) {
  29072. _this.scene.removeLight(o);
  29073. });
  29074. this.meshes.forEach(function (o) {
  29075. _this.scene.removeMesh(o);
  29076. });
  29077. this.skeletons.forEach(function (o) {
  29078. _this.scene.removeSkeleton(o);
  29079. });
  29080. this.particleSystems.forEach(function (o) {
  29081. _this.scene.removeParticleSystem(o);
  29082. });
  29083. this.animations.forEach(function (o) {
  29084. _this.scene.removeAnimation(o);
  29085. });
  29086. this.animationGroups.forEach(function (o) {
  29087. _this.scene.removeAnimationGroup(o);
  29088. });
  29089. this.multiMaterials.forEach(function (o) {
  29090. _this.scene.removeMultiMaterial(o);
  29091. });
  29092. this.materials.forEach(function (o) {
  29093. _this.scene.removeMaterial(o);
  29094. });
  29095. this.morphTargetManagers.forEach(function (o) {
  29096. _this.scene.removeMorphTargetManager(o);
  29097. });
  29098. this.geometries.forEach(function (o) {
  29099. _this.scene.removeGeometry(o);
  29100. });
  29101. this.transformNodes.forEach(function (o) {
  29102. _this.scene.removeTransformNode(o);
  29103. });
  29104. this.lensFlareSystems.forEach(function (o) {
  29105. _this.scene.removeLensFlareSystem(o);
  29106. });
  29107. this.actionManagers.forEach(function (o) {
  29108. _this.scene.removeActionManager(o);
  29109. });
  29110. this.sounds.forEach(function (o) {
  29111. o.stop();
  29112. o.autoplay = false;
  29113. _this.scene.mainSoundTrack.RemoveSound(o);
  29114. });
  29115. this.textures.forEach(function (o) {
  29116. _this.scene.removeTexture(o);
  29117. });
  29118. this.effectLayers.forEach(function (o) {
  29119. _this.scene.removeEffectLayer(o);
  29120. });
  29121. };
  29122. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29123. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29124. var asset = sourceAssets_1[_i];
  29125. var move = true;
  29126. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29127. var keepAsset = keepAssets_1[_a];
  29128. if (asset === keepAsset) {
  29129. move = false;
  29130. break;
  29131. }
  29132. }
  29133. if (move) {
  29134. targetAssets.push(asset);
  29135. }
  29136. }
  29137. };
  29138. /**
  29139. * Removes all the assets contained in the scene and adds them to the container.
  29140. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29141. */
  29142. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29143. if (keepAssets === undefined) {
  29144. keepAssets = new KeepAssets();
  29145. }
  29146. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29147. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29148. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29149. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29150. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29151. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29152. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29153. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29154. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29155. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29156. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29157. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29158. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29159. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29160. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29161. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29162. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29163. this.removeAllFromScene();
  29164. };
  29165. return AssetContainer;
  29166. }());
  29167. BABYLON.AssetContainer = AssetContainer;
  29168. })(BABYLON || (BABYLON = {}));
  29169. //# sourceMappingURL=babylon.assetContainer.js.map
  29170. var BABYLON;
  29171. (function (BABYLON) {
  29172. var Buffer = /** @class */ (function () {
  29173. /**
  29174. * Constructor
  29175. * @param engine the engine
  29176. * @param data the data to use for this buffer
  29177. * @param updatable whether the data is updatable
  29178. * @param stride the stride (optional)
  29179. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29180. * @param instanced whether the buffer is instanced (optional)
  29181. * @param useBytes set to true if the stride in in bytes (optional)
  29182. */
  29183. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29184. if (stride === void 0) { stride = 0; }
  29185. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29186. if (instanced === void 0) { instanced = false; }
  29187. if (useBytes === void 0) { useBytes = false; }
  29188. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29189. this._engine = engine.getScene().getEngine();
  29190. }
  29191. else {
  29192. this._engine = engine;
  29193. }
  29194. this._updatable = updatable;
  29195. this._instanced = instanced;
  29196. this._data = data;
  29197. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29198. if (!postponeInternalCreation) { // by default
  29199. this.create();
  29200. }
  29201. }
  29202. /**
  29203. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29204. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29205. * @param offset defines offset in the buffer (0 by default)
  29206. * @param size defines the size in floats of attributes (position is 3 for instance)
  29207. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29208. * @param instanced defines if the vertex buffer contains indexed data
  29209. * @param useBytes defines if the offset and stride are in bytes
  29210. * @returns the new vertex buffer
  29211. */
  29212. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29213. if (useBytes === void 0) { useBytes = false; }
  29214. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29215. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29216. // a lot of these parameters are ignored as they are overriden by the buffer
  29217. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29218. };
  29219. // Properties
  29220. Buffer.prototype.isUpdatable = function () {
  29221. return this._updatable;
  29222. };
  29223. Buffer.prototype.getData = function () {
  29224. return this._data;
  29225. };
  29226. Buffer.prototype.getBuffer = function () {
  29227. return this._buffer;
  29228. };
  29229. /**
  29230. * Gets the stride in float32 units (i.e. byte stride / 4).
  29231. * May not be an integer if the byte stride is not divisible by 4.
  29232. * DEPRECATED. Use byteStride instead.
  29233. * @returns the stride in float32 units
  29234. */
  29235. Buffer.prototype.getStrideSize = function () {
  29236. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29237. };
  29238. // Methods
  29239. Buffer.prototype.create = function (data) {
  29240. if (data === void 0) { data = null; }
  29241. if (!data && this._buffer) {
  29242. return; // nothing to do
  29243. }
  29244. data = data || this._data;
  29245. if (!data) {
  29246. return;
  29247. }
  29248. if (!this._buffer) { // create buffer
  29249. if (this._updatable) {
  29250. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29251. this._data = data;
  29252. }
  29253. else {
  29254. this._buffer = this._engine.createVertexBuffer(data);
  29255. }
  29256. }
  29257. else if (this._updatable) { // update buffer
  29258. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29259. this._data = data;
  29260. }
  29261. };
  29262. Buffer.prototype._rebuild = function () {
  29263. this._buffer = null;
  29264. this.create(this._data);
  29265. };
  29266. Buffer.prototype.update = function (data) {
  29267. this.create(data);
  29268. };
  29269. /**
  29270. * Updates the data directly.
  29271. * @param data the new data
  29272. * @param offset the new offset
  29273. * @param vertexCount the vertex count (optional)
  29274. * @param useBytes set to true if the offset is in bytes
  29275. */
  29276. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29277. if (useBytes === void 0) { useBytes = false; }
  29278. if (!this._buffer) {
  29279. return;
  29280. }
  29281. if (this._updatable) { // update buffer
  29282. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29283. this._data = null;
  29284. }
  29285. };
  29286. Buffer.prototype.dispose = function () {
  29287. if (!this._buffer) {
  29288. return;
  29289. }
  29290. if (this._engine._releaseBuffer(this._buffer)) {
  29291. this._buffer = null;
  29292. }
  29293. };
  29294. return Buffer;
  29295. }());
  29296. BABYLON.Buffer = Buffer;
  29297. })(BABYLON || (BABYLON = {}));
  29298. //# sourceMappingURL=babylon.buffer.js.map
  29299. var BABYLON;
  29300. (function (BABYLON) {
  29301. var VertexBuffer = /** @class */ (function () {
  29302. /**
  29303. * Constructor
  29304. * @param engine the engine
  29305. * @param data the data to use for this vertex buffer
  29306. * @param kind the vertex buffer kind
  29307. * @param updatable whether the data is updatable
  29308. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29309. * @param stride the stride (optional)
  29310. * @param instanced whether the buffer is instanced (optional)
  29311. * @param offset the offset of the data (optional)
  29312. * @param size the number of components (optional)
  29313. * @param type the type of the component (optional)
  29314. * @param normalized whether the data contains normalized data (optional)
  29315. * @param useBytes set to true if stride and offset are in bytes (optional)
  29316. */
  29317. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29318. if (normalized === void 0) { normalized = false; }
  29319. if (useBytes === void 0) { useBytes = false; }
  29320. if (data instanceof BABYLON.Buffer) {
  29321. this._buffer = data;
  29322. this._ownsBuffer = false;
  29323. }
  29324. else {
  29325. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29326. this._ownsBuffer = true;
  29327. }
  29328. this._kind = kind;
  29329. if (type == undefined) {
  29330. var data_1 = this.getData();
  29331. this.type = VertexBuffer.FLOAT;
  29332. if (data_1 instanceof Int8Array)
  29333. this.type = VertexBuffer.BYTE;
  29334. else if (data_1 instanceof Uint8Array)
  29335. this.type = VertexBuffer.UNSIGNED_BYTE;
  29336. else if (data_1 instanceof Int16Array)
  29337. this.type = VertexBuffer.SHORT;
  29338. else if (data_1 instanceof Uint16Array)
  29339. this.type = VertexBuffer.UNSIGNED_SHORT;
  29340. else if (data_1 instanceof Int32Array)
  29341. this.type = VertexBuffer.INT;
  29342. else if (data_1 instanceof Uint32Array)
  29343. this.type = VertexBuffer.UNSIGNED_INT;
  29344. }
  29345. else {
  29346. this.type = type;
  29347. }
  29348. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29349. if (useBytes) {
  29350. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29351. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29352. this.byteOffset = offset || 0;
  29353. }
  29354. else {
  29355. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29356. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29357. this.byteOffset = (offset || 0) * typeByteLength;
  29358. }
  29359. this.normalized = normalized;
  29360. this._instanced = instanced !== undefined ? instanced : false;
  29361. this._instanceDivisor = instanced ? 1 : 0;
  29362. }
  29363. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29364. /**
  29365. * Gets or sets the instance divisor when in instanced mode
  29366. */
  29367. get: function () {
  29368. return this._instanceDivisor;
  29369. },
  29370. set: function (value) {
  29371. this._instanceDivisor = value;
  29372. if (value == 0) {
  29373. this._instanced = false;
  29374. }
  29375. else {
  29376. this._instanced = true;
  29377. }
  29378. },
  29379. enumerable: true,
  29380. configurable: true
  29381. });
  29382. VertexBuffer.prototype._rebuild = function () {
  29383. if (!this._buffer) {
  29384. return;
  29385. }
  29386. this._buffer._rebuild();
  29387. };
  29388. /**
  29389. * Returns the kind of the VertexBuffer (string).
  29390. */
  29391. VertexBuffer.prototype.getKind = function () {
  29392. return this._kind;
  29393. };
  29394. // Properties
  29395. /**
  29396. * Boolean : is the VertexBuffer updatable ?
  29397. */
  29398. VertexBuffer.prototype.isUpdatable = function () {
  29399. return this._buffer.isUpdatable();
  29400. };
  29401. /**
  29402. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29403. */
  29404. VertexBuffer.prototype.getData = function () {
  29405. return this._buffer.getData();
  29406. };
  29407. /**
  29408. * Returns the WebGLBuffer associated to the VertexBuffer.
  29409. */
  29410. VertexBuffer.prototype.getBuffer = function () {
  29411. return this._buffer.getBuffer();
  29412. };
  29413. /**
  29414. * Returns the stride as a multiple of the type byte length.
  29415. * DEPRECATED. Use byteStride instead.
  29416. */
  29417. VertexBuffer.prototype.getStrideSize = function () {
  29418. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29419. };
  29420. /**
  29421. * Returns the offset as a multiple of the type byte length.
  29422. * DEPRECATED. Use byteOffset instead.
  29423. */
  29424. VertexBuffer.prototype.getOffset = function () {
  29425. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29426. };
  29427. /**
  29428. * Returns the number of components per vertex attribute (integer).
  29429. */
  29430. VertexBuffer.prototype.getSize = function () {
  29431. return this._size;
  29432. };
  29433. /**
  29434. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29435. */
  29436. VertexBuffer.prototype.getIsInstanced = function () {
  29437. return this._instanced;
  29438. };
  29439. /**
  29440. * Returns the instancing divisor, zero for non-instanced (integer).
  29441. */
  29442. VertexBuffer.prototype.getInstanceDivisor = function () {
  29443. return this._instanceDivisor;
  29444. };
  29445. // Methods
  29446. /**
  29447. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29448. * Returns the created WebGLBuffer.
  29449. */
  29450. VertexBuffer.prototype.create = function (data) {
  29451. return this._buffer.create(data);
  29452. };
  29453. /**
  29454. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29455. * This function will create a new buffer if the current one is not updatable
  29456. * Returns the updated WebGLBuffer.
  29457. */
  29458. VertexBuffer.prototype.update = function (data) {
  29459. return this._buffer.update(data);
  29460. };
  29461. /**
  29462. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29463. * Returns the directly updated WebGLBuffer.
  29464. * @param data the new data
  29465. * @param offset the new offset
  29466. * @param useBytes set to true if the offset is in bytes
  29467. */
  29468. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29469. if (useBytes === void 0) { useBytes = false; }
  29470. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29471. };
  29472. /**
  29473. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29474. */
  29475. VertexBuffer.prototype.dispose = function () {
  29476. if (this._ownsBuffer) {
  29477. this._buffer.dispose();
  29478. }
  29479. };
  29480. /**
  29481. * Enumerates each value of this vertex buffer as numbers.
  29482. * @param count the number of values to enumerate
  29483. * @param callback the callback function called for each value
  29484. */
  29485. VertexBuffer.prototype.forEach = function (count, callback) {
  29486. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29487. };
  29488. Object.defineProperty(VertexBuffer, "PositionKind", {
  29489. get: function () {
  29490. return VertexBuffer._PositionKind;
  29491. },
  29492. enumerable: true,
  29493. configurable: true
  29494. });
  29495. Object.defineProperty(VertexBuffer, "NormalKind", {
  29496. get: function () {
  29497. return VertexBuffer._NormalKind;
  29498. },
  29499. enumerable: true,
  29500. configurable: true
  29501. });
  29502. Object.defineProperty(VertexBuffer, "TangentKind", {
  29503. get: function () {
  29504. return VertexBuffer._TangentKind;
  29505. },
  29506. enumerable: true,
  29507. configurable: true
  29508. });
  29509. Object.defineProperty(VertexBuffer, "UVKind", {
  29510. get: function () {
  29511. return VertexBuffer._UVKind;
  29512. },
  29513. enumerable: true,
  29514. configurable: true
  29515. });
  29516. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29517. get: function () {
  29518. return VertexBuffer._UV2Kind;
  29519. },
  29520. enumerable: true,
  29521. configurable: true
  29522. });
  29523. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29524. get: function () {
  29525. return VertexBuffer._UV3Kind;
  29526. },
  29527. enumerable: true,
  29528. configurable: true
  29529. });
  29530. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29531. get: function () {
  29532. return VertexBuffer._UV4Kind;
  29533. },
  29534. enumerable: true,
  29535. configurable: true
  29536. });
  29537. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29538. get: function () {
  29539. return VertexBuffer._UV5Kind;
  29540. },
  29541. enumerable: true,
  29542. configurable: true
  29543. });
  29544. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29545. get: function () {
  29546. return VertexBuffer._UV6Kind;
  29547. },
  29548. enumerable: true,
  29549. configurable: true
  29550. });
  29551. Object.defineProperty(VertexBuffer, "ColorKind", {
  29552. get: function () {
  29553. return VertexBuffer._ColorKind;
  29554. },
  29555. enumerable: true,
  29556. configurable: true
  29557. });
  29558. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29559. get: function () {
  29560. return VertexBuffer._MatricesIndicesKind;
  29561. },
  29562. enumerable: true,
  29563. configurable: true
  29564. });
  29565. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29566. get: function () {
  29567. return VertexBuffer._MatricesWeightsKind;
  29568. },
  29569. enumerable: true,
  29570. configurable: true
  29571. });
  29572. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29573. get: function () {
  29574. return VertexBuffer._MatricesIndicesExtraKind;
  29575. },
  29576. enumerable: true,
  29577. configurable: true
  29578. });
  29579. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29580. get: function () {
  29581. return VertexBuffer._MatricesWeightsExtraKind;
  29582. },
  29583. enumerable: true,
  29584. configurable: true
  29585. });
  29586. /**
  29587. * Deduces the stride given a kind.
  29588. * @param kind The kind string to deduce
  29589. * @returns The deduced stride
  29590. */
  29591. VertexBuffer.DeduceStride = function (kind) {
  29592. switch (kind) {
  29593. case VertexBuffer.UVKind:
  29594. case VertexBuffer.UV2Kind:
  29595. case VertexBuffer.UV3Kind:
  29596. case VertexBuffer.UV4Kind:
  29597. case VertexBuffer.UV5Kind:
  29598. case VertexBuffer.UV6Kind:
  29599. return 2;
  29600. case VertexBuffer.NormalKind:
  29601. case VertexBuffer.PositionKind:
  29602. return 3;
  29603. case VertexBuffer.ColorKind:
  29604. case VertexBuffer.MatricesIndicesKind:
  29605. case VertexBuffer.MatricesIndicesExtraKind:
  29606. case VertexBuffer.MatricesWeightsKind:
  29607. case VertexBuffer.MatricesWeightsExtraKind:
  29608. case VertexBuffer.TangentKind:
  29609. return 4;
  29610. default:
  29611. throw new Error("Invalid kind '" + kind + "'");
  29612. }
  29613. };
  29614. /**
  29615. * Gets the byte length of the given type.
  29616. * @param type the type
  29617. * @returns the number of bytes
  29618. */
  29619. VertexBuffer.GetTypeByteLength = function (type) {
  29620. switch (type) {
  29621. case VertexBuffer.BYTE:
  29622. case VertexBuffer.UNSIGNED_BYTE:
  29623. return 1;
  29624. case VertexBuffer.SHORT:
  29625. case VertexBuffer.UNSIGNED_SHORT:
  29626. return 2;
  29627. case VertexBuffer.INT:
  29628. case VertexBuffer.FLOAT:
  29629. return 4;
  29630. default:
  29631. throw new Error("Invalid type '" + type + "'");
  29632. }
  29633. };
  29634. /**
  29635. * Enumerates each value of the given parameters as numbers.
  29636. * @param data the data to enumerate
  29637. * @param byteOffset the byte offset of the data
  29638. * @param byteStride the byte stride of the data
  29639. * @param componentCount the number of components per element
  29640. * @param componentType the type of the component
  29641. * @param count the total number of components
  29642. * @param normalized whether the data is normalized
  29643. * @param callback the callback function called for each value
  29644. */
  29645. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29646. if (data instanceof Array) {
  29647. var offset = byteOffset / 4;
  29648. var stride = byteStride / 4;
  29649. for (var index = 0; index < count; index += componentCount) {
  29650. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29651. callback(data[offset + componentIndex], index + componentIndex);
  29652. }
  29653. offset += stride;
  29654. }
  29655. }
  29656. else {
  29657. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29658. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29659. for (var index = 0; index < count; index += componentCount) {
  29660. var componentByteOffset = byteOffset;
  29661. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29662. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29663. callback(value, index + componentIndex);
  29664. componentByteOffset += componentByteLength;
  29665. }
  29666. byteOffset += byteStride;
  29667. }
  29668. }
  29669. };
  29670. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29671. switch (type) {
  29672. case VertexBuffer.BYTE: {
  29673. var value = dataView.getInt8(byteOffset);
  29674. if (normalized) {
  29675. value = Math.max(value / 127, -1);
  29676. }
  29677. return value;
  29678. }
  29679. case VertexBuffer.UNSIGNED_BYTE: {
  29680. var value = dataView.getUint8(byteOffset);
  29681. if (normalized) {
  29682. value = value / 255;
  29683. }
  29684. return value;
  29685. }
  29686. case VertexBuffer.SHORT: {
  29687. var value = dataView.getInt16(byteOffset, true);
  29688. if (normalized) {
  29689. value = Math.max(value / 16383, -1);
  29690. }
  29691. return value;
  29692. }
  29693. case VertexBuffer.UNSIGNED_SHORT: {
  29694. var value = dataView.getUint16(byteOffset, true);
  29695. if (normalized) {
  29696. value = value / 65535;
  29697. }
  29698. return value;
  29699. }
  29700. case VertexBuffer.FLOAT: {
  29701. return dataView.getFloat32(byteOffset, true);
  29702. }
  29703. default: {
  29704. throw new Error("Invalid component type " + type);
  29705. }
  29706. }
  29707. };
  29708. /**
  29709. * The byte type.
  29710. */
  29711. VertexBuffer.BYTE = 5120;
  29712. /**
  29713. * The unsigned byte type.
  29714. */
  29715. VertexBuffer.UNSIGNED_BYTE = 5121;
  29716. /**
  29717. * The short type.
  29718. */
  29719. VertexBuffer.SHORT = 5122;
  29720. /**
  29721. * The unsigned short type.
  29722. */
  29723. VertexBuffer.UNSIGNED_SHORT = 5123;
  29724. /**
  29725. * The integer type.
  29726. */
  29727. VertexBuffer.INT = 5124;
  29728. /**
  29729. * The unsigned integer type.
  29730. */
  29731. VertexBuffer.UNSIGNED_INT = 5125;
  29732. /**
  29733. * The float type.
  29734. */
  29735. VertexBuffer.FLOAT = 5126;
  29736. // Enums
  29737. VertexBuffer._PositionKind = "position";
  29738. VertexBuffer._NormalKind = "normal";
  29739. VertexBuffer._TangentKind = "tangent";
  29740. VertexBuffer._UVKind = "uv";
  29741. VertexBuffer._UV2Kind = "uv2";
  29742. VertexBuffer._UV3Kind = "uv3";
  29743. VertexBuffer._UV4Kind = "uv4";
  29744. VertexBuffer._UV5Kind = "uv5";
  29745. VertexBuffer._UV6Kind = "uv6";
  29746. VertexBuffer._ColorKind = "color";
  29747. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29748. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29749. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29750. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29751. return VertexBuffer;
  29752. }());
  29753. BABYLON.VertexBuffer = VertexBuffer;
  29754. })(BABYLON || (BABYLON = {}));
  29755. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29756. var BABYLON;
  29757. (function (BABYLON) {
  29758. /**
  29759. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29760. */
  29761. var DummyInternalTextureTracker = /** @class */ (function () {
  29762. function DummyInternalTextureTracker() {
  29763. /**
  29764. * Gets or set the previous tracker in the list
  29765. */
  29766. this.previous = null;
  29767. /**
  29768. * Gets or set the next tracker in the list
  29769. */
  29770. this.next = null;
  29771. }
  29772. return DummyInternalTextureTracker;
  29773. }());
  29774. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29775. })(BABYLON || (BABYLON = {}));
  29776. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29777. var BABYLON;
  29778. (function (BABYLON) {
  29779. /**
  29780. * Class used to store data associated with WebGL texture data for the engine
  29781. * This class should not be used directly
  29782. */
  29783. var InternalTexture = /** @class */ (function () {
  29784. /**
  29785. * Creates a new InternalTexture
  29786. * @param engine defines the engine to use
  29787. * @param dataSource defines the type of data that will be used
  29788. */
  29789. function InternalTexture(engine, dataSource) {
  29790. /**
  29791. * Observable called when the texture is loaded
  29792. */
  29793. this.onLoadedObservable = new BABYLON.Observable();
  29794. /**
  29795. * Gets or set the previous tracker in the list
  29796. */
  29797. this.previous = null;
  29798. /**
  29799. * Gets or set the next tracker in the list
  29800. */
  29801. this.next = null;
  29802. // Private
  29803. /** @hidden */
  29804. this._initialSlot = -1;
  29805. /** @hidden */
  29806. this._designatedSlot = -1;
  29807. /** @hidden */
  29808. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29809. /** @hidden */
  29810. this._comparisonFunction = 0;
  29811. /** @hidden */
  29812. this._references = 1;
  29813. this._engine = engine;
  29814. this._dataSource = dataSource;
  29815. this._webGLTexture = engine._createTexture();
  29816. }
  29817. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29818. /**
  29819. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29820. */
  29821. get: function () {
  29822. return this._dataSource;
  29823. },
  29824. enumerable: true,
  29825. configurable: true
  29826. });
  29827. /**
  29828. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29829. */
  29830. InternalTexture.prototype.incrementReferences = function () {
  29831. this._references++;
  29832. };
  29833. /**
  29834. * Change the size of the texture (not the size of the content)
  29835. * @param width defines the new width
  29836. * @param height defines the new height
  29837. * @param depth defines the new depth (1 by default)
  29838. */
  29839. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29840. if (depth === void 0) { depth = 1; }
  29841. this.width = width;
  29842. this.height = height;
  29843. this.depth = depth;
  29844. this.baseWidth = width;
  29845. this.baseHeight = height;
  29846. this.baseDepth = depth;
  29847. this._size = width * height * depth;
  29848. };
  29849. /** @hidden */
  29850. InternalTexture.prototype._rebuild = function () {
  29851. var _this = this;
  29852. var proxy;
  29853. this.isReady = false;
  29854. this._cachedCoordinatesMode = null;
  29855. this._cachedWrapU = null;
  29856. this._cachedWrapV = null;
  29857. this._cachedAnisotropicFilteringLevel = null;
  29858. switch (this._dataSource) {
  29859. case InternalTexture.DATASOURCE_TEMP:
  29860. return;
  29861. case InternalTexture.DATASOURCE_URL:
  29862. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29863. _this.isReady = true;
  29864. }, null, this._buffer, undefined, this.format);
  29865. proxy._swapAndDie(this);
  29866. return;
  29867. case InternalTexture.DATASOURCE_RAW:
  29868. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29869. proxy._swapAndDie(this);
  29870. this.isReady = true;
  29871. return;
  29872. case InternalTexture.DATASOURCE_RAW3D:
  29873. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29874. proxy._swapAndDie(this);
  29875. this.isReady = true;
  29876. return;
  29877. case InternalTexture.DATASOURCE_DYNAMIC:
  29878. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29879. proxy._swapAndDie(this);
  29880. // The engine will make sure to update content so no need to flag it as isReady = true
  29881. return;
  29882. case InternalTexture.DATASOURCE_RENDERTARGET:
  29883. var options = new BABYLON.RenderTargetCreationOptions();
  29884. options.generateDepthBuffer = this._generateDepthBuffer;
  29885. options.generateMipMaps = this.generateMipMaps;
  29886. options.generateStencilBuffer = this._generateStencilBuffer;
  29887. options.samplingMode = this.samplingMode;
  29888. options.type = this.type;
  29889. if (this.isCube) {
  29890. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29891. }
  29892. else {
  29893. var size = {
  29894. width: this.width,
  29895. height: this.height
  29896. };
  29897. proxy = this._engine.createRenderTargetTexture(size, options);
  29898. }
  29899. proxy._swapAndDie(this);
  29900. this.isReady = true;
  29901. return;
  29902. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29903. var depthTextureOptions = {
  29904. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29905. comparisonFunction: this._comparisonFunction,
  29906. generateStencil: this._generateStencilBuffer,
  29907. isCube: this.isCube
  29908. };
  29909. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29910. proxy._swapAndDie(this);
  29911. this.isReady = true;
  29912. return;
  29913. case InternalTexture.DATASOURCE_CUBE:
  29914. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29915. _this.isReady = true;
  29916. }, null, this.format, this._extension);
  29917. proxy._swapAndDie(this);
  29918. return;
  29919. case InternalTexture.DATASOURCE_CUBERAW:
  29920. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29921. proxy._swapAndDie(this);
  29922. this.isReady = true;
  29923. return;
  29924. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29925. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29926. if (proxy) {
  29927. proxy._swapAndDie(_this);
  29928. }
  29929. _this.isReady = true;
  29930. }, null, this.format, this._extension);
  29931. return;
  29932. }
  29933. };
  29934. InternalTexture.prototype._swapAndDie = function (target) {
  29935. target._webGLTexture = this._webGLTexture;
  29936. if (this._framebuffer) {
  29937. target._framebuffer = this._framebuffer;
  29938. }
  29939. if (this._depthStencilBuffer) {
  29940. target._depthStencilBuffer = this._depthStencilBuffer;
  29941. }
  29942. if (this._lodTextureHigh) {
  29943. if (target._lodTextureHigh) {
  29944. target._lodTextureHigh.dispose();
  29945. }
  29946. target._lodTextureHigh = this._lodTextureHigh;
  29947. }
  29948. if (this._lodTextureMid) {
  29949. if (target._lodTextureMid) {
  29950. target._lodTextureMid.dispose();
  29951. }
  29952. target._lodTextureMid = this._lodTextureMid;
  29953. }
  29954. if (this._lodTextureLow) {
  29955. if (target._lodTextureLow) {
  29956. target._lodTextureLow.dispose();
  29957. }
  29958. target._lodTextureLow = this._lodTextureLow;
  29959. }
  29960. var cache = this._engine.getLoadedTexturesCache();
  29961. var index = cache.indexOf(this);
  29962. if (index !== -1) {
  29963. cache.splice(index, 1);
  29964. }
  29965. };
  29966. /**
  29967. * Dispose the current allocated resources
  29968. */
  29969. InternalTexture.prototype.dispose = function () {
  29970. if (!this._webGLTexture) {
  29971. return;
  29972. }
  29973. this._references--;
  29974. if (this._references === 0) {
  29975. this._engine._releaseTexture(this);
  29976. this._webGLTexture = null;
  29977. this.previous = null;
  29978. this.next = null;
  29979. }
  29980. };
  29981. /**
  29982. * The source of the texture data is unknown
  29983. */
  29984. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29985. /**
  29986. * Texture data comes from an URL
  29987. */
  29988. InternalTexture.DATASOURCE_URL = 1;
  29989. /**
  29990. * Texture data is only used for temporary storage
  29991. */
  29992. InternalTexture.DATASOURCE_TEMP = 2;
  29993. /**
  29994. * Texture data comes from raw data (ArrayBuffer)
  29995. */
  29996. InternalTexture.DATASOURCE_RAW = 3;
  29997. /**
  29998. * Texture content is dynamic (video or dynamic texture)
  29999. */
  30000. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30001. /**
  30002. * Texture content is generated by rendering to it
  30003. */
  30004. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30005. /**
  30006. * Texture content is part of a multi render target process
  30007. */
  30008. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30009. /**
  30010. * Texture data comes from a cube data file
  30011. */
  30012. InternalTexture.DATASOURCE_CUBE = 7;
  30013. /**
  30014. * Texture data comes from a raw cube data
  30015. */
  30016. InternalTexture.DATASOURCE_CUBERAW = 8;
  30017. /**
  30018. * Texture data come from a prefiltered cube data file
  30019. */
  30020. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30021. /**
  30022. * Texture content is raw 3D data
  30023. */
  30024. InternalTexture.DATASOURCE_RAW3D = 10;
  30025. /**
  30026. * Texture content is a depth texture
  30027. */
  30028. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30029. return InternalTexture;
  30030. }());
  30031. BABYLON.InternalTexture = InternalTexture;
  30032. })(BABYLON || (BABYLON = {}));
  30033. //# sourceMappingURL=babylon.internalTexture.js.map
  30034. var BABYLON;
  30035. (function (BABYLON) {
  30036. var BaseTexture = /** @class */ (function () {
  30037. function BaseTexture(scene) {
  30038. this._hasAlpha = false;
  30039. this.getAlphaFromRGB = false;
  30040. this.level = 1;
  30041. this.coordinatesIndex = 0;
  30042. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30043. /**
  30044. * | Value | Type | Description |
  30045. * | ----- | ------------------ | ----------- |
  30046. * | 0 | CLAMP_ADDRESSMODE | |
  30047. * | 1 | WRAP_ADDRESSMODE | |
  30048. * | 2 | MIRROR_ADDRESSMODE | |
  30049. */
  30050. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30051. /**
  30052. * | Value | Type | Description |
  30053. * | ----- | ------------------ | ----------- |
  30054. * | 0 | CLAMP_ADDRESSMODE | |
  30055. * | 1 | WRAP_ADDRESSMODE | |
  30056. * | 2 | MIRROR_ADDRESSMODE | |
  30057. */
  30058. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30059. /**
  30060. * | Value | Type | Description |
  30061. * | ----- | ------------------ | ----------- |
  30062. * | 0 | CLAMP_ADDRESSMODE | |
  30063. * | 1 | WRAP_ADDRESSMODE | |
  30064. * | 2 | MIRROR_ADDRESSMODE | |
  30065. */
  30066. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30067. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30068. this.isCube = false;
  30069. this.is3D = false;
  30070. this.gammaSpace = true;
  30071. this.invertZ = false;
  30072. this.lodLevelInAlpha = false;
  30073. this.lodGenerationOffset = 0.0;
  30074. this.lodGenerationScale = 0.8;
  30075. this.isRenderTarget = false;
  30076. this.animations = new Array();
  30077. /**
  30078. * An event triggered when the texture is disposed.
  30079. */
  30080. this.onDisposeObservable = new BABYLON.Observable();
  30081. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30082. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30083. if (this._scene) {
  30084. this._scene.textures.push(this);
  30085. }
  30086. this._uid = null;
  30087. }
  30088. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30089. get: function () {
  30090. return this._hasAlpha;
  30091. },
  30092. set: function (value) {
  30093. if (this._hasAlpha === value) {
  30094. return;
  30095. }
  30096. this._hasAlpha = value;
  30097. if (this._scene) {
  30098. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30099. }
  30100. },
  30101. enumerable: true,
  30102. configurable: true
  30103. });
  30104. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30105. get: function () {
  30106. return this._coordinatesMode;
  30107. },
  30108. /**
  30109. * How a texture is mapped.
  30110. *
  30111. * | Value | Type | Description |
  30112. * | ----- | ----------------------------------- | ----------- |
  30113. * | 0 | EXPLICIT_MODE | |
  30114. * | 1 | SPHERICAL_MODE | |
  30115. * | 2 | PLANAR_MODE | |
  30116. * | 3 | CUBIC_MODE | |
  30117. * | 4 | PROJECTION_MODE | |
  30118. * | 5 | SKYBOX_MODE | |
  30119. * | 6 | INVCUBIC_MODE | |
  30120. * | 7 | EQUIRECTANGULAR_MODE | |
  30121. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30122. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30123. */
  30124. set: function (value) {
  30125. if (this._coordinatesMode === value) {
  30126. return;
  30127. }
  30128. this._coordinatesMode = value;
  30129. if (this._scene) {
  30130. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30131. }
  30132. },
  30133. enumerable: true,
  30134. configurable: true
  30135. });
  30136. Object.defineProperty(BaseTexture.prototype, "uid", {
  30137. get: function () {
  30138. if (!this._uid) {
  30139. this._uid = BABYLON.Tools.RandomId();
  30140. }
  30141. return this._uid;
  30142. },
  30143. enumerable: true,
  30144. configurable: true
  30145. });
  30146. BaseTexture.prototype.toString = function () {
  30147. return this.name;
  30148. };
  30149. BaseTexture.prototype.getClassName = function () {
  30150. return "BaseTexture";
  30151. };
  30152. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30153. set: function (callback) {
  30154. if (this._onDisposeObserver) {
  30155. this.onDisposeObservable.remove(this._onDisposeObserver);
  30156. }
  30157. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30158. },
  30159. enumerable: true,
  30160. configurable: true
  30161. });
  30162. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30163. get: function () {
  30164. return true;
  30165. },
  30166. enumerable: true,
  30167. configurable: true
  30168. });
  30169. BaseTexture.prototype.getScene = function () {
  30170. return this._scene;
  30171. };
  30172. BaseTexture.prototype.getTextureMatrix = function () {
  30173. return BABYLON.Matrix.IdentityReadOnly;
  30174. };
  30175. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30176. return BABYLON.Matrix.IdentityReadOnly;
  30177. };
  30178. BaseTexture.prototype.getInternalTexture = function () {
  30179. return this._texture;
  30180. };
  30181. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30182. return !this.isBlocking || this.isReady();
  30183. };
  30184. BaseTexture.prototype.isReady = function () {
  30185. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30186. this.delayLoad();
  30187. return false;
  30188. }
  30189. if (this._texture) {
  30190. return this._texture.isReady;
  30191. }
  30192. return false;
  30193. };
  30194. BaseTexture.prototype.getSize = function () {
  30195. if (this._texture && this._texture.width) {
  30196. return new BABYLON.Size(this._texture.width, this._texture.height);
  30197. }
  30198. if (this._texture && this._texture._size) {
  30199. return new BABYLON.Size(this._texture._size, this._texture._size);
  30200. }
  30201. return BABYLON.Size.Zero();
  30202. };
  30203. BaseTexture.prototype.getBaseSize = function () {
  30204. if (!this.isReady() || !this._texture)
  30205. return BABYLON.Size.Zero();
  30206. if (this._texture._size) {
  30207. return new BABYLON.Size(this._texture._size, this._texture._size);
  30208. }
  30209. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30210. };
  30211. BaseTexture.prototype.scale = function (ratio) {
  30212. };
  30213. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30214. get: function () {
  30215. return false;
  30216. },
  30217. enumerable: true,
  30218. configurable: true
  30219. });
  30220. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30221. if (!this._scene) {
  30222. return null;
  30223. }
  30224. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30225. for (var index = 0; index < texturesCache.length; index++) {
  30226. var texturesCacheEntry = texturesCache[index];
  30227. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30228. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30229. texturesCacheEntry.incrementReferences();
  30230. return texturesCacheEntry;
  30231. }
  30232. }
  30233. }
  30234. return null;
  30235. };
  30236. BaseTexture.prototype._rebuild = function () {
  30237. };
  30238. BaseTexture.prototype.delayLoad = function () {
  30239. };
  30240. BaseTexture.prototype.clone = function () {
  30241. return null;
  30242. };
  30243. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30244. get: function () {
  30245. if (!this._texture) {
  30246. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30247. }
  30248. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30249. },
  30250. enumerable: true,
  30251. configurable: true
  30252. });
  30253. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30254. get: function () {
  30255. if (!this._texture) {
  30256. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30257. }
  30258. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30259. },
  30260. enumerable: true,
  30261. configurable: true
  30262. });
  30263. BaseTexture.prototype.readPixels = function (faceIndex) {
  30264. if (faceIndex === void 0) { faceIndex = 0; }
  30265. if (!this._texture) {
  30266. return null;
  30267. }
  30268. var size = this.getSize();
  30269. var scene = this.getScene();
  30270. if (!scene) {
  30271. return null;
  30272. }
  30273. var engine = scene.getEngine();
  30274. if (this._texture.isCube) {
  30275. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30276. }
  30277. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30278. };
  30279. BaseTexture.prototype.releaseInternalTexture = function () {
  30280. if (this._texture) {
  30281. this._texture.dispose();
  30282. this._texture = null;
  30283. }
  30284. };
  30285. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30286. get: function () {
  30287. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30288. return null;
  30289. }
  30290. if (!this._texture._sphericalPolynomial) {
  30291. this._texture._sphericalPolynomial =
  30292. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30293. }
  30294. return this._texture._sphericalPolynomial;
  30295. },
  30296. set: function (value) {
  30297. if (this._texture) {
  30298. this._texture._sphericalPolynomial = value;
  30299. }
  30300. },
  30301. enumerable: true,
  30302. configurable: true
  30303. });
  30304. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30305. get: function () {
  30306. if (this._texture) {
  30307. return this._texture._lodTextureHigh;
  30308. }
  30309. return null;
  30310. },
  30311. enumerable: true,
  30312. configurable: true
  30313. });
  30314. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30315. get: function () {
  30316. if (this._texture) {
  30317. return this._texture._lodTextureMid;
  30318. }
  30319. return null;
  30320. },
  30321. enumerable: true,
  30322. configurable: true
  30323. });
  30324. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30325. get: function () {
  30326. if (this._texture) {
  30327. return this._texture._lodTextureLow;
  30328. }
  30329. return null;
  30330. },
  30331. enumerable: true,
  30332. configurable: true
  30333. });
  30334. BaseTexture.prototype.dispose = function () {
  30335. if (!this._scene) {
  30336. return;
  30337. }
  30338. // Animations
  30339. this._scene.stopAnimation(this);
  30340. // Remove from scene
  30341. this._scene._removePendingData(this);
  30342. var index = this._scene.textures.indexOf(this);
  30343. if (index >= 0) {
  30344. this._scene.textures.splice(index, 1);
  30345. }
  30346. if (this._texture === undefined) {
  30347. return;
  30348. }
  30349. // Release
  30350. this.releaseInternalTexture();
  30351. // Callback
  30352. this.onDisposeObservable.notifyObservers(this);
  30353. this.onDisposeObservable.clear();
  30354. };
  30355. BaseTexture.prototype.serialize = function () {
  30356. if (!this.name) {
  30357. return null;
  30358. }
  30359. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30360. // Animations
  30361. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30362. return serializationObject;
  30363. };
  30364. BaseTexture.WhenAllReady = function (textures, callback) {
  30365. var numRemaining = textures.length;
  30366. if (numRemaining === 0) {
  30367. callback();
  30368. return;
  30369. }
  30370. var _loop_1 = function () {
  30371. texture = textures[i];
  30372. if (texture.isReady()) {
  30373. if (--numRemaining === 0) {
  30374. callback();
  30375. }
  30376. }
  30377. else {
  30378. onLoadObservable = texture.onLoadObservable;
  30379. var onLoadCallback_1 = function () {
  30380. onLoadObservable.removeCallback(onLoadCallback_1);
  30381. if (--numRemaining === 0) {
  30382. callback();
  30383. }
  30384. };
  30385. onLoadObservable.add(onLoadCallback_1);
  30386. }
  30387. };
  30388. var texture, onLoadObservable;
  30389. for (var i = 0; i < textures.length; i++) {
  30390. _loop_1();
  30391. }
  30392. };
  30393. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30394. __decorate([
  30395. BABYLON.serialize()
  30396. ], BaseTexture.prototype, "name", void 0);
  30397. __decorate([
  30398. BABYLON.serialize("hasAlpha")
  30399. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30400. __decorate([
  30401. BABYLON.serialize()
  30402. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30403. __decorate([
  30404. BABYLON.serialize()
  30405. ], BaseTexture.prototype, "level", void 0);
  30406. __decorate([
  30407. BABYLON.serialize()
  30408. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30409. __decorate([
  30410. BABYLON.serialize("coordinatesMode")
  30411. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30412. __decorate([
  30413. BABYLON.serialize()
  30414. ], BaseTexture.prototype, "wrapU", void 0);
  30415. __decorate([
  30416. BABYLON.serialize()
  30417. ], BaseTexture.prototype, "wrapV", void 0);
  30418. __decorate([
  30419. BABYLON.serialize()
  30420. ], BaseTexture.prototype, "wrapR", void 0);
  30421. __decorate([
  30422. BABYLON.serialize()
  30423. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30424. __decorate([
  30425. BABYLON.serialize()
  30426. ], BaseTexture.prototype, "isCube", void 0);
  30427. __decorate([
  30428. BABYLON.serialize()
  30429. ], BaseTexture.prototype, "is3D", void 0);
  30430. __decorate([
  30431. BABYLON.serialize()
  30432. ], BaseTexture.prototype, "gammaSpace", void 0);
  30433. __decorate([
  30434. BABYLON.serialize()
  30435. ], BaseTexture.prototype, "invertZ", void 0);
  30436. __decorate([
  30437. BABYLON.serialize()
  30438. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30439. __decorate([
  30440. BABYLON.serialize()
  30441. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30442. __decorate([
  30443. BABYLON.serialize()
  30444. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30445. __decorate([
  30446. BABYLON.serialize()
  30447. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30448. return BaseTexture;
  30449. }());
  30450. BABYLON.BaseTexture = BaseTexture;
  30451. })(BABYLON || (BABYLON = {}));
  30452. //# sourceMappingURL=babylon.baseTexture.js.map
  30453. var BABYLON;
  30454. (function (BABYLON) {
  30455. var Texture = /** @class */ (function (_super) {
  30456. __extends(Texture, _super);
  30457. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30458. if (noMipmap === void 0) { noMipmap = false; }
  30459. if (invertY === void 0) { invertY = true; }
  30460. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30461. if (onLoad === void 0) { onLoad = null; }
  30462. if (onError === void 0) { onError = null; }
  30463. if (buffer === void 0) { buffer = null; }
  30464. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30465. var _this = _super.call(this, scene) || this;
  30466. _this.uOffset = 0;
  30467. _this.vOffset = 0;
  30468. _this.uScale = 1.0;
  30469. _this.vScale = 1.0;
  30470. _this.uAng = 0;
  30471. _this.vAng = 0;
  30472. _this.wAng = 0;
  30473. _this._isBlocking = true;
  30474. _this.name = url || "";
  30475. _this.url = url;
  30476. _this._noMipmap = noMipmap;
  30477. _this._invertY = invertY;
  30478. _this._samplingMode = samplingMode;
  30479. _this._buffer = buffer;
  30480. _this._deleteBuffer = deleteBuffer;
  30481. if (format) {
  30482. _this._format = format;
  30483. }
  30484. scene = _this.getScene();
  30485. if (!scene) {
  30486. return _this;
  30487. }
  30488. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30489. var load = function () {
  30490. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30491. _this.onLoadObservable.notifyObservers(_this);
  30492. }
  30493. if (onLoad) {
  30494. onLoad();
  30495. }
  30496. if (!_this.isBlocking && scene) {
  30497. scene.resetCachedMaterial();
  30498. }
  30499. };
  30500. if (!_this.url) {
  30501. _this._delayedOnLoad = load;
  30502. _this._delayedOnError = onError;
  30503. return _this;
  30504. }
  30505. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30506. if (!_this._texture) {
  30507. if (!scene.useDelayedTextureLoading) {
  30508. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30509. if (deleteBuffer) {
  30510. delete _this._buffer;
  30511. }
  30512. }
  30513. else {
  30514. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30515. _this._delayedOnLoad = load;
  30516. _this._delayedOnError = onError;
  30517. }
  30518. }
  30519. else {
  30520. if (_this._texture.isReady) {
  30521. BABYLON.Tools.SetImmediate(function () { return load(); });
  30522. }
  30523. else {
  30524. _this._texture.onLoadedObservable.add(load);
  30525. }
  30526. }
  30527. return _this;
  30528. }
  30529. Object.defineProperty(Texture.prototype, "noMipmap", {
  30530. get: function () {
  30531. return this._noMipmap;
  30532. },
  30533. enumerable: true,
  30534. configurable: true
  30535. });
  30536. Object.defineProperty(Texture.prototype, "isBlocking", {
  30537. get: function () {
  30538. return this._isBlocking;
  30539. },
  30540. set: function (value) {
  30541. this._isBlocking = value;
  30542. },
  30543. enumerable: true,
  30544. configurable: true
  30545. });
  30546. Object.defineProperty(Texture.prototype, "samplingMode", {
  30547. get: function () {
  30548. return this._samplingMode;
  30549. },
  30550. enumerable: true,
  30551. configurable: true
  30552. });
  30553. Texture.prototype.updateURL = function (url) {
  30554. this.url = url;
  30555. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30556. this.delayLoad();
  30557. };
  30558. Texture.prototype.delayLoad = function () {
  30559. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30560. return;
  30561. }
  30562. var scene = this.getScene();
  30563. if (!scene) {
  30564. return;
  30565. }
  30566. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30567. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30568. if (!this._texture) {
  30569. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30570. if (this._deleteBuffer) {
  30571. delete this._buffer;
  30572. }
  30573. }
  30574. else {
  30575. if (this._delayedOnLoad) {
  30576. if (this._texture.isReady) {
  30577. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30578. }
  30579. else {
  30580. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30581. }
  30582. }
  30583. }
  30584. this._delayedOnLoad = null;
  30585. this._delayedOnError = null;
  30586. };
  30587. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30588. if (!this._texture) {
  30589. return;
  30590. }
  30591. var scene = this.getScene();
  30592. if (!scene) {
  30593. return;
  30594. }
  30595. this._samplingMode = samplingMode;
  30596. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30597. };
  30598. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30599. x *= this.uScale;
  30600. y *= this.vScale;
  30601. x -= 0.5 * this.uScale;
  30602. y -= 0.5 * this.vScale;
  30603. z -= 0.5;
  30604. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30605. t.x += 0.5 * this.uScale + this.uOffset;
  30606. t.y += 0.5 * this.vScale + this.vOffset;
  30607. t.z += 0.5;
  30608. };
  30609. Texture.prototype.getTextureMatrix = function () {
  30610. var _this = this;
  30611. if (this.uOffset === this._cachedUOffset &&
  30612. this.vOffset === this._cachedVOffset &&
  30613. this.uScale === this._cachedUScale &&
  30614. this.vScale === this._cachedVScale &&
  30615. this.uAng === this._cachedUAng &&
  30616. this.vAng === this._cachedVAng &&
  30617. this.wAng === this._cachedWAng) {
  30618. return this._cachedTextureMatrix;
  30619. }
  30620. this._cachedUOffset = this.uOffset;
  30621. this._cachedVOffset = this.vOffset;
  30622. this._cachedUScale = this.uScale;
  30623. this._cachedVScale = this.vScale;
  30624. this._cachedUAng = this.uAng;
  30625. this._cachedVAng = this.vAng;
  30626. this._cachedWAng = this.wAng;
  30627. if (!this._cachedTextureMatrix) {
  30628. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30629. this._rowGenerationMatrix = new BABYLON.Matrix();
  30630. this._t0 = BABYLON.Vector3.Zero();
  30631. this._t1 = BABYLON.Vector3.Zero();
  30632. this._t2 = BABYLON.Vector3.Zero();
  30633. }
  30634. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30635. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30636. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30637. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30638. this._t1.subtractInPlace(this._t0);
  30639. this._t2.subtractInPlace(this._t0);
  30640. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30641. this._cachedTextureMatrix.m[0] = this._t1.x;
  30642. this._cachedTextureMatrix.m[1] = this._t1.y;
  30643. this._cachedTextureMatrix.m[2] = this._t1.z;
  30644. this._cachedTextureMatrix.m[4] = this._t2.x;
  30645. this._cachedTextureMatrix.m[5] = this._t2.y;
  30646. this._cachedTextureMatrix.m[6] = this._t2.z;
  30647. this._cachedTextureMatrix.m[8] = this._t0.x;
  30648. this._cachedTextureMatrix.m[9] = this._t0.y;
  30649. this._cachedTextureMatrix.m[10] = this._t0.z;
  30650. var scene = this.getScene();
  30651. if (!scene) {
  30652. return this._cachedTextureMatrix;
  30653. }
  30654. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30655. return mat.hasTexture(_this);
  30656. });
  30657. return this._cachedTextureMatrix;
  30658. };
  30659. Texture.prototype.getReflectionTextureMatrix = function () {
  30660. var _this = this;
  30661. var scene = this.getScene();
  30662. if (!scene) {
  30663. return this._cachedTextureMatrix;
  30664. }
  30665. if (this.uOffset === this._cachedUOffset &&
  30666. this.vOffset === this._cachedVOffset &&
  30667. this.uScale === this._cachedUScale &&
  30668. this.vScale === this._cachedVScale &&
  30669. this.coordinatesMode === this._cachedCoordinatesMode) {
  30670. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30671. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30672. return this._cachedTextureMatrix;
  30673. }
  30674. }
  30675. else {
  30676. return this._cachedTextureMatrix;
  30677. }
  30678. }
  30679. if (!this._cachedTextureMatrix) {
  30680. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30681. }
  30682. if (!this._projectionModeMatrix) {
  30683. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30684. }
  30685. this._cachedUOffset = this.uOffset;
  30686. this._cachedVOffset = this.vOffset;
  30687. this._cachedUScale = this.uScale;
  30688. this._cachedVScale = this.vScale;
  30689. this._cachedCoordinatesMode = this.coordinatesMode;
  30690. switch (this.coordinatesMode) {
  30691. case Texture.PLANAR_MODE:
  30692. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30693. this._cachedTextureMatrix[0] = this.uScale;
  30694. this._cachedTextureMatrix[5] = this.vScale;
  30695. this._cachedTextureMatrix[12] = this.uOffset;
  30696. this._cachedTextureMatrix[13] = this.vOffset;
  30697. break;
  30698. case Texture.PROJECTION_MODE:
  30699. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30700. this._projectionModeMatrix.m[0] = 0.5;
  30701. this._projectionModeMatrix.m[5] = -0.5;
  30702. this._projectionModeMatrix.m[10] = 0.0;
  30703. this._projectionModeMatrix.m[12] = 0.5;
  30704. this._projectionModeMatrix.m[13] = 0.5;
  30705. this._projectionModeMatrix.m[14] = 1.0;
  30706. this._projectionModeMatrix.m[15] = 1.0;
  30707. var projectionMatrix = scene.getProjectionMatrix();
  30708. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30709. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30710. break;
  30711. default:
  30712. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30713. break;
  30714. }
  30715. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30716. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30717. });
  30718. return this._cachedTextureMatrix;
  30719. };
  30720. Texture.prototype.clone = function () {
  30721. var _this = this;
  30722. return BABYLON.SerializationHelper.Clone(function () {
  30723. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30724. }, this);
  30725. };
  30726. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30727. get: function () {
  30728. if (!this._onLoadObservable) {
  30729. this._onLoadObservable = new BABYLON.Observable();
  30730. }
  30731. return this._onLoadObservable;
  30732. },
  30733. enumerable: true,
  30734. configurable: true
  30735. });
  30736. Texture.prototype.serialize = function () {
  30737. var serializationObject = _super.prototype.serialize.call(this);
  30738. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30739. serializationObject.base64String = this._buffer;
  30740. serializationObject.name = serializationObject.name.replace("data:", "");
  30741. }
  30742. serializationObject.invertY = this._invertY;
  30743. serializationObject.samplingMode = this.samplingMode;
  30744. return serializationObject;
  30745. };
  30746. Texture.prototype.getClassName = function () {
  30747. return "Texture";
  30748. };
  30749. Texture.prototype.dispose = function () {
  30750. _super.prototype.dispose.call(this);
  30751. if (this.onLoadObservable) {
  30752. this.onLoadObservable.clear();
  30753. this._onLoadObservable = null;
  30754. }
  30755. this._delayedOnLoad = null;
  30756. this._delayedOnError = null;
  30757. };
  30758. // Statics
  30759. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30760. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30761. if (onLoad === void 0) { onLoad = null; }
  30762. if (onError === void 0) { onError = null; }
  30763. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30764. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30765. };
  30766. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30767. if (parsedTexture.customType) {
  30768. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30769. // Update Sampling Mode
  30770. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30771. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30772. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30773. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30774. }
  30775. }
  30776. return parsedCustomTexture;
  30777. }
  30778. if (parsedTexture.isCube) {
  30779. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30780. }
  30781. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30782. return null;
  30783. }
  30784. var texture = BABYLON.SerializationHelper.Parse(function () {
  30785. var generateMipMaps = true;
  30786. if (parsedTexture.noMipmap) {
  30787. generateMipMaps = false;
  30788. }
  30789. if (parsedTexture.mirrorPlane) {
  30790. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30791. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30792. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30793. return mirrorTexture;
  30794. }
  30795. else if (parsedTexture.isRenderTarget) {
  30796. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30797. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30798. return renderTargetTexture;
  30799. }
  30800. else {
  30801. var texture;
  30802. if (parsedTexture.base64String) {
  30803. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30804. }
  30805. else {
  30806. var url = rootUrl + parsedTexture.name;
  30807. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30808. url = parsedTexture.url;
  30809. }
  30810. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30811. }
  30812. return texture;
  30813. }
  30814. }, parsedTexture, scene);
  30815. // Update Sampling Mode
  30816. if (parsedTexture.samplingMode) {
  30817. var sampling = parsedTexture.samplingMode;
  30818. if (texture._samplingMode !== sampling) {
  30819. texture.updateSamplingMode(sampling);
  30820. }
  30821. }
  30822. // Animations
  30823. if (parsedTexture.animations) {
  30824. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30825. var parsedAnimation = parsedTexture.animations[animationIndex];
  30826. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30827. }
  30828. }
  30829. return texture;
  30830. };
  30831. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30832. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30833. if (noMipmap === void 0) { noMipmap = false; }
  30834. if (invertY === void 0) { invertY = true; }
  30835. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30836. if (onLoad === void 0) { onLoad = null; }
  30837. if (onError === void 0) { onError = null; }
  30838. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30839. if (name.substr(0, 5) !== "data:") {
  30840. name = "data:" + name;
  30841. }
  30842. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30843. };
  30844. // Constants
  30845. Texture.NEAREST_SAMPLINGMODE = 1;
  30846. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30847. Texture.BILINEAR_SAMPLINGMODE = 2;
  30848. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30849. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30850. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30851. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30852. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30853. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30854. Texture.NEAREST_LINEAR = 7;
  30855. Texture.NEAREST_NEAREST = 8;
  30856. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30857. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30858. Texture.LINEAR_LINEAR = 11;
  30859. Texture.LINEAR_NEAREST = 12;
  30860. Texture.EXPLICIT_MODE = 0;
  30861. Texture.SPHERICAL_MODE = 1;
  30862. Texture.PLANAR_MODE = 2;
  30863. Texture.CUBIC_MODE = 3;
  30864. Texture.PROJECTION_MODE = 4;
  30865. Texture.SKYBOX_MODE = 5;
  30866. Texture.INVCUBIC_MODE = 6;
  30867. Texture.EQUIRECTANGULAR_MODE = 7;
  30868. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30869. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30870. Texture.CLAMP_ADDRESSMODE = 0;
  30871. Texture.WRAP_ADDRESSMODE = 1;
  30872. Texture.MIRROR_ADDRESSMODE = 2;
  30873. /**
  30874. * 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
  30875. */
  30876. Texture.UseSerializedUrlIfAny = false;
  30877. __decorate([
  30878. BABYLON.serialize()
  30879. ], Texture.prototype, "url", void 0);
  30880. __decorate([
  30881. BABYLON.serialize()
  30882. ], Texture.prototype, "uOffset", void 0);
  30883. __decorate([
  30884. BABYLON.serialize()
  30885. ], Texture.prototype, "vOffset", void 0);
  30886. __decorate([
  30887. BABYLON.serialize()
  30888. ], Texture.prototype, "uScale", void 0);
  30889. __decorate([
  30890. BABYLON.serialize()
  30891. ], Texture.prototype, "vScale", void 0);
  30892. __decorate([
  30893. BABYLON.serialize()
  30894. ], Texture.prototype, "uAng", void 0);
  30895. __decorate([
  30896. BABYLON.serialize()
  30897. ], Texture.prototype, "vAng", void 0);
  30898. __decorate([
  30899. BABYLON.serialize()
  30900. ], Texture.prototype, "wAng", void 0);
  30901. __decorate([
  30902. BABYLON.serialize()
  30903. ], Texture.prototype, "isBlocking", null);
  30904. return Texture;
  30905. }(BABYLON.BaseTexture));
  30906. BABYLON.Texture = Texture;
  30907. })(BABYLON || (BABYLON = {}));
  30908. //# sourceMappingURL=babylon.texture.js.map
  30909. var BABYLON;
  30910. (function (BABYLON) {
  30911. /**
  30912. * @hidden
  30913. **/
  30914. var _InstancesBatch = /** @class */ (function () {
  30915. function _InstancesBatch() {
  30916. this.mustReturn = false;
  30917. this.visibleInstances = new Array();
  30918. this.renderSelf = new Array();
  30919. }
  30920. return _InstancesBatch;
  30921. }());
  30922. BABYLON._InstancesBatch = _InstancesBatch;
  30923. var Mesh = /** @class */ (function (_super) {
  30924. __extends(Mesh, _super);
  30925. /**
  30926. * @constructor
  30927. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30928. * @param {Scene} scene The scene to add this mesh to.
  30929. * @param {Node} parent The parent of this mesh, if it has one
  30930. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30931. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30932. * When false, achieved by calling a clone(), also passing False.
  30933. * This will make creation of children, recursive.
  30934. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30935. */
  30936. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30937. if (scene === void 0) { scene = null; }
  30938. if (parent === void 0) { parent = null; }
  30939. if (source === void 0) { source = null; }
  30940. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30941. var _this = _super.call(this, name, scene) || this;
  30942. // Events
  30943. /**
  30944. * An event triggered before rendering the mesh
  30945. */
  30946. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30947. /**
  30948. * An event triggered after rendering the mesh
  30949. */
  30950. _this.onAfterRenderObservable = new BABYLON.Observable();
  30951. /**
  30952. * An event triggered before drawing the mesh
  30953. */
  30954. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30955. // Members
  30956. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30957. _this.instances = new Array();
  30958. _this._LODLevels = new Array();
  30959. _this._visibleInstances = {};
  30960. _this._renderIdForInstances = new Array();
  30961. _this._batchCache = new _InstancesBatch();
  30962. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30963. // Use by builder only to know what orientation were the mesh build in.
  30964. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30965. _this.overrideMaterialSideOrientation = null;
  30966. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30967. // Will be used to save a source mesh reference, If any
  30968. _this._source = null;
  30969. scene = _this.getScene();
  30970. if (source) {
  30971. // Source mesh
  30972. _this._source = source;
  30973. // Geometry
  30974. if (source._geometry) {
  30975. source._geometry.applyToMesh(_this);
  30976. }
  30977. // Deep copy
  30978. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30979. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30980. // Metadata
  30981. if (source.metadata && source.metadata.clone) {
  30982. _this.metadata = source.metadata.clone();
  30983. }
  30984. else {
  30985. _this.metadata = source.metadata;
  30986. }
  30987. // Tags
  30988. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30989. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30990. }
  30991. // Parent
  30992. _this.parent = source.parent;
  30993. // Pivot
  30994. _this.setPivotMatrix(source.getPivotMatrix());
  30995. _this.id = name + "." + source.id;
  30996. // Material
  30997. _this.material = source.material;
  30998. var index;
  30999. if (!doNotCloneChildren) {
  31000. // Children
  31001. var directDescendants = source.getDescendants(true);
  31002. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31003. var child = directDescendants[index_1];
  31004. if (child.clone) {
  31005. child.clone(name + "." + child.name, _this);
  31006. }
  31007. }
  31008. }
  31009. // Physics clone
  31010. var physicsEngine = _this.getScene().getPhysicsEngine();
  31011. if (clonePhysicsImpostor && physicsEngine) {
  31012. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31013. if (impostor) {
  31014. _this.physicsImpostor = impostor.clone(_this);
  31015. }
  31016. }
  31017. // Particles
  31018. for (index = 0; index < scene.particleSystems.length; index++) {
  31019. var system = scene.particleSystems[index];
  31020. if (system.emitter === source) {
  31021. system.clone(system.name, _this);
  31022. }
  31023. }
  31024. _this.computeWorldMatrix(true);
  31025. }
  31026. // Parent
  31027. if (parent !== null) {
  31028. _this.parent = parent;
  31029. }
  31030. return _this;
  31031. }
  31032. Object.defineProperty(Mesh, "FRONTSIDE", {
  31033. /**
  31034. * Mesh side orientation : usually the external or front surface
  31035. */
  31036. get: function () {
  31037. return Mesh._FRONTSIDE;
  31038. },
  31039. enumerable: true,
  31040. configurable: true
  31041. });
  31042. Object.defineProperty(Mesh, "BACKSIDE", {
  31043. /**
  31044. * Mesh side orientation : usually the internal or back surface
  31045. */
  31046. get: function () {
  31047. return Mesh._BACKSIDE;
  31048. },
  31049. enumerable: true,
  31050. configurable: true
  31051. });
  31052. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31053. /**
  31054. * Mesh side orientation : both internal and external or front and back surfaces
  31055. */
  31056. get: function () {
  31057. return Mesh._DOUBLESIDE;
  31058. },
  31059. enumerable: true,
  31060. configurable: true
  31061. });
  31062. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31063. /**
  31064. * Mesh side orientation : by default, `FRONTSIDE`
  31065. */
  31066. get: function () {
  31067. return Mesh._DEFAULTSIDE;
  31068. },
  31069. enumerable: true,
  31070. configurable: true
  31071. });
  31072. Object.defineProperty(Mesh, "NO_CAP", {
  31073. /**
  31074. * Mesh cap setting : no cap
  31075. */
  31076. get: function () {
  31077. return Mesh._NO_CAP;
  31078. },
  31079. enumerable: true,
  31080. configurable: true
  31081. });
  31082. Object.defineProperty(Mesh, "CAP_START", {
  31083. /**
  31084. * Mesh cap setting : one cap at the beginning of the mesh
  31085. */
  31086. get: function () {
  31087. return Mesh._CAP_START;
  31088. },
  31089. enumerable: true,
  31090. configurable: true
  31091. });
  31092. Object.defineProperty(Mesh, "CAP_END", {
  31093. /**
  31094. * Mesh cap setting : one cap at the end of the mesh
  31095. */
  31096. get: function () {
  31097. return Mesh._CAP_END;
  31098. },
  31099. enumerable: true,
  31100. configurable: true
  31101. });
  31102. Object.defineProperty(Mesh, "CAP_ALL", {
  31103. /**
  31104. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31105. */
  31106. get: function () {
  31107. return Mesh._CAP_ALL;
  31108. },
  31109. enumerable: true,
  31110. configurable: true
  31111. });
  31112. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31113. set: function (callback) {
  31114. if (this._onBeforeDrawObserver) {
  31115. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31116. }
  31117. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31118. },
  31119. enumerable: true,
  31120. configurable: true
  31121. });
  31122. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31123. get: function () {
  31124. return this._morphTargetManager;
  31125. },
  31126. set: function (value) {
  31127. if (this._morphTargetManager === value) {
  31128. return;
  31129. }
  31130. this._morphTargetManager = value;
  31131. this._syncGeometryWithMorphTargetManager();
  31132. },
  31133. enumerable: true,
  31134. configurable: true
  31135. });
  31136. Object.defineProperty(Mesh.prototype, "source", {
  31137. get: function () {
  31138. return this._source;
  31139. },
  31140. enumerable: true,
  31141. configurable: true
  31142. });
  31143. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31144. get: function () {
  31145. return this._unIndexed;
  31146. },
  31147. set: function (value) {
  31148. if (this._unIndexed !== value) {
  31149. this._unIndexed = value;
  31150. this._markSubMeshesAsAttributesDirty();
  31151. }
  31152. },
  31153. enumerable: true,
  31154. configurable: true
  31155. });
  31156. // Methods
  31157. /**
  31158. * Returns the string "Mesh".
  31159. */
  31160. Mesh.prototype.getClassName = function () {
  31161. return "Mesh";
  31162. };
  31163. /**
  31164. * Returns a string.
  31165. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31166. */
  31167. Mesh.prototype.toString = function (fullDetails) {
  31168. var ret = _super.prototype.toString.call(this, fullDetails);
  31169. ret += ", n vertices: " + this.getTotalVertices();
  31170. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31171. if (this.animations) {
  31172. for (var i = 0; i < this.animations.length; i++) {
  31173. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31174. }
  31175. }
  31176. if (fullDetails) {
  31177. if (this._geometry) {
  31178. var ib = this.getIndices();
  31179. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31180. if (vb && ib) {
  31181. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31182. }
  31183. }
  31184. else {
  31185. ret += ", flat shading: UNKNOWN";
  31186. }
  31187. }
  31188. return ret;
  31189. };
  31190. Mesh.prototype._unBindEffect = function () {
  31191. _super.prototype._unBindEffect.call(this);
  31192. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31193. var instance = _a[_i];
  31194. instance._unBindEffect();
  31195. }
  31196. };
  31197. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31198. /**
  31199. * True if the mesh has some Levels Of Details (LOD).
  31200. * Returns a boolean.
  31201. */
  31202. get: function () {
  31203. return this._LODLevels.length > 0;
  31204. },
  31205. enumerable: true,
  31206. configurable: true
  31207. });
  31208. /**
  31209. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31210. * @returns an array of {BABYLON.MeshLODLevel}
  31211. */
  31212. Mesh.prototype.getLODLevels = function () {
  31213. return this._LODLevels;
  31214. };
  31215. Mesh.prototype._sortLODLevels = function () {
  31216. this._LODLevels.sort(function (a, b) {
  31217. if (a.distance < b.distance) {
  31218. return 1;
  31219. }
  31220. if (a.distance > b.distance) {
  31221. return -1;
  31222. }
  31223. return 0;
  31224. });
  31225. };
  31226. /**
  31227. * Add a mesh as LOD level triggered at the given distance.
  31228. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31229. * @param {number} distance The distance from the center of the object to show this level
  31230. * @param {Mesh} mesh The mesh to be added as LOD level
  31231. * @return {Mesh} This mesh (for chaining)
  31232. */
  31233. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31234. if (mesh && mesh._masterMesh) {
  31235. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31236. return this;
  31237. }
  31238. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31239. this._LODLevels.push(level);
  31240. if (mesh) {
  31241. mesh._masterMesh = this;
  31242. }
  31243. this._sortLODLevels();
  31244. return this;
  31245. };
  31246. /**
  31247. * Returns the LOD level mesh at the passed distance or null if not found.
  31248. * It is related to the method `addLODLevel(distance, mesh)`.
  31249. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31250. * Returns an object Mesh or `null`.
  31251. */
  31252. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31253. for (var index = 0; index < this._LODLevels.length; index++) {
  31254. var level = this._LODLevels[index];
  31255. if (level.distance === distance) {
  31256. return level.mesh;
  31257. }
  31258. }
  31259. return null;
  31260. };
  31261. /**
  31262. * Remove a mesh from the LOD array
  31263. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31264. * @param {Mesh} mesh The mesh to be removed.
  31265. * @return {Mesh} This mesh (for chaining)
  31266. */
  31267. Mesh.prototype.removeLODLevel = function (mesh) {
  31268. for (var index = 0; index < this._LODLevels.length; index++) {
  31269. if (this._LODLevels[index].mesh === mesh) {
  31270. this._LODLevels.splice(index, 1);
  31271. if (mesh) {
  31272. mesh._masterMesh = null;
  31273. }
  31274. }
  31275. }
  31276. this._sortLODLevels();
  31277. return this;
  31278. };
  31279. /**
  31280. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31281. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31282. */
  31283. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31284. if (!this._LODLevels || this._LODLevels.length === 0) {
  31285. return this;
  31286. }
  31287. var bSphere;
  31288. if (boundingSphere) {
  31289. bSphere = boundingSphere;
  31290. }
  31291. else {
  31292. var boundingInfo = this.getBoundingInfo();
  31293. bSphere = boundingInfo.boundingSphere;
  31294. }
  31295. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31296. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31297. if (this.onLODLevelSelection) {
  31298. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31299. }
  31300. return this;
  31301. }
  31302. for (var index = 0; index < this._LODLevels.length; index++) {
  31303. var level = this._LODLevels[index];
  31304. if (level.distance < distanceToCamera) {
  31305. if (level.mesh) {
  31306. level.mesh._preActivate();
  31307. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31308. }
  31309. if (this.onLODLevelSelection) {
  31310. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31311. }
  31312. return level.mesh;
  31313. }
  31314. }
  31315. if (this.onLODLevelSelection) {
  31316. this.onLODLevelSelection(distanceToCamera, this, this);
  31317. }
  31318. return this;
  31319. };
  31320. Object.defineProperty(Mesh.prototype, "geometry", {
  31321. /**
  31322. * Returns the mesh internal Geometry object.
  31323. */
  31324. get: function () {
  31325. return this._geometry;
  31326. },
  31327. enumerable: true,
  31328. configurable: true
  31329. });
  31330. /**
  31331. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31332. */
  31333. Mesh.prototype.getTotalVertices = function () {
  31334. if (this._geometry === null || this._geometry === undefined) {
  31335. return 0;
  31336. }
  31337. return this._geometry.getTotalVertices();
  31338. };
  31339. /**
  31340. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31341. * 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.
  31342. * You can force the copy with forceCopy === true
  31343. * Returns null if the mesh has no geometry or no vertex buffer.
  31344. * Possible `kind` values :
  31345. * - BABYLON.VertexBuffer.PositionKind
  31346. * - BABYLON.VertexBuffer.UVKind
  31347. * - BABYLON.VertexBuffer.UV2Kind
  31348. * - BABYLON.VertexBuffer.UV3Kind
  31349. * - BABYLON.VertexBuffer.UV4Kind
  31350. * - BABYLON.VertexBuffer.UV5Kind
  31351. * - BABYLON.VertexBuffer.UV6Kind
  31352. * - BABYLON.VertexBuffer.ColorKind
  31353. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31354. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31355. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31356. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31357. */
  31358. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31359. if (!this._geometry) {
  31360. return null;
  31361. }
  31362. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31363. };
  31364. /**
  31365. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31366. * Returns `null` if the mesh has no geometry.
  31367. * Possible `kind` values :
  31368. * - BABYLON.VertexBuffer.PositionKind
  31369. * - BABYLON.VertexBuffer.UVKind
  31370. * - BABYLON.VertexBuffer.UV2Kind
  31371. * - BABYLON.VertexBuffer.UV3Kind
  31372. * - BABYLON.VertexBuffer.UV4Kind
  31373. * - BABYLON.VertexBuffer.UV5Kind
  31374. * - BABYLON.VertexBuffer.UV6Kind
  31375. * - BABYLON.VertexBuffer.ColorKind
  31376. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31377. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31378. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31379. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31380. */
  31381. Mesh.prototype.getVertexBuffer = function (kind) {
  31382. if (!this._geometry) {
  31383. return null;
  31384. }
  31385. return this._geometry.getVertexBuffer(kind);
  31386. };
  31387. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31388. if (!this._geometry) {
  31389. if (this._delayInfo) {
  31390. return this._delayInfo.indexOf(kind) !== -1;
  31391. }
  31392. return false;
  31393. }
  31394. return this._geometry.isVerticesDataPresent(kind);
  31395. };
  31396. /**
  31397. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31398. * Possible `kind` values :
  31399. * - BABYLON.VertexBuffer.PositionKind
  31400. * - BABYLON.VertexBuffer.UVKind
  31401. * - BABYLON.VertexBuffer.UV2Kind
  31402. * - BABYLON.VertexBuffer.UV3Kind
  31403. * - BABYLON.VertexBuffer.UV4Kind
  31404. * - BABYLON.VertexBuffer.UV5Kind
  31405. * - BABYLON.VertexBuffer.UV6Kind
  31406. * - BABYLON.VertexBuffer.ColorKind
  31407. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31408. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31409. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31410. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31411. */
  31412. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31413. if (!this._geometry) {
  31414. if (this._delayInfo) {
  31415. return this._delayInfo.indexOf(kind) !== -1;
  31416. }
  31417. return false;
  31418. }
  31419. return this._geometry.isVertexBufferUpdatable(kind);
  31420. };
  31421. /**
  31422. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31423. * Possible `kind` values :
  31424. * - BABYLON.VertexBuffer.PositionKind
  31425. * - BABYLON.VertexBuffer.UVKind
  31426. * - BABYLON.VertexBuffer.UV2Kind
  31427. * - BABYLON.VertexBuffer.UV3Kind
  31428. * - BABYLON.VertexBuffer.UV4Kind
  31429. * - BABYLON.VertexBuffer.UV5Kind
  31430. * - BABYLON.VertexBuffer.UV6Kind
  31431. * - BABYLON.VertexBuffer.ColorKind
  31432. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31433. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31434. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31435. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31436. */
  31437. Mesh.prototype.getVerticesDataKinds = function () {
  31438. if (!this._geometry) {
  31439. var result = new Array();
  31440. if (this._delayInfo) {
  31441. this._delayInfo.forEach(function (kind, index, array) {
  31442. result.push(kind);
  31443. });
  31444. }
  31445. return result;
  31446. }
  31447. return this._geometry.getVerticesDataKinds();
  31448. };
  31449. /**
  31450. * Returns a positive integer : the total number of indices in this mesh geometry.
  31451. * Returns zero if the mesh has no geometry.
  31452. */
  31453. Mesh.prototype.getTotalIndices = function () {
  31454. if (!this._geometry) {
  31455. return 0;
  31456. }
  31457. return this._geometry.getTotalIndices();
  31458. };
  31459. /**
  31460. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31461. * 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.
  31462. * Returns an empty array if the mesh has no geometry.
  31463. */
  31464. Mesh.prototype.getIndices = function (copyWhenShared) {
  31465. if (!this._geometry) {
  31466. return [];
  31467. }
  31468. return this._geometry.getIndices(copyWhenShared);
  31469. };
  31470. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31471. get: function () {
  31472. return this._masterMesh !== null && this._masterMesh !== undefined;
  31473. },
  31474. enumerable: true,
  31475. configurable: true
  31476. });
  31477. /**
  31478. * Determine if the current mesh is ready to be rendered
  31479. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31480. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31481. * @returns true if all associated assets are ready (material, textures, shaders)
  31482. */
  31483. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31484. if (completeCheck === void 0) { completeCheck = false; }
  31485. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31486. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31487. return false;
  31488. }
  31489. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31490. return false;
  31491. }
  31492. if (!this.subMeshes || this.subMeshes.length === 0) {
  31493. return true;
  31494. }
  31495. if (!completeCheck) {
  31496. return true;
  31497. }
  31498. var engine = this.getEngine();
  31499. var scene = this.getScene();
  31500. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31501. this.computeWorldMatrix();
  31502. var mat = this.material || scene.defaultMaterial;
  31503. if (mat) {
  31504. if (mat.storeEffectOnSubMeshes) {
  31505. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31506. var subMesh = _a[_i];
  31507. var effectiveMaterial = subMesh.getMaterial();
  31508. if (effectiveMaterial) {
  31509. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31510. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31511. return false;
  31512. }
  31513. }
  31514. else {
  31515. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31516. return false;
  31517. }
  31518. }
  31519. }
  31520. }
  31521. }
  31522. else {
  31523. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31524. return false;
  31525. }
  31526. }
  31527. }
  31528. // Shadows
  31529. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31530. var light = _c[_b];
  31531. var generator = light.getShadowGenerator();
  31532. if (generator) {
  31533. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31534. var subMesh = _e[_d];
  31535. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31536. return false;
  31537. }
  31538. }
  31539. }
  31540. }
  31541. // LOD
  31542. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31543. var lod = _g[_f];
  31544. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31545. return false;
  31546. }
  31547. }
  31548. return true;
  31549. };
  31550. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31551. /**
  31552. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31553. * This property is pertinent only for updatable parametric shapes.
  31554. */
  31555. get: function () {
  31556. return this._areNormalsFrozen;
  31557. },
  31558. enumerable: true,
  31559. configurable: true
  31560. });
  31561. /**
  31562. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31563. * It has no effect at all on other shapes.
  31564. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31565. * Returns the Mesh.
  31566. */
  31567. Mesh.prototype.freezeNormals = function () {
  31568. this._areNormalsFrozen = true;
  31569. return this;
  31570. };
  31571. /**
  31572. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31573. * It has no effect at all on other shapes.
  31574. * It reactivates the mesh normals computation if it was previously frozen.
  31575. * Returns the Mesh.
  31576. */
  31577. Mesh.prototype.unfreezeNormals = function () {
  31578. this._areNormalsFrozen = false;
  31579. return this;
  31580. };
  31581. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31582. /**
  31583. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31584. */
  31585. set: function (count) {
  31586. this._overridenInstanceCount = count;
  31587. },
  31588. enumerable: true,
  31589. configurable: true
  31590. });
  31591. // Methods
  31592. Mesh.prototype._preActivate = function () {
  31593. var sceneRenderId = this.getScene().getRenderId();
  31594. if (this._preActivateId === sceneRenderId) {
  31595. return this;
  31596. }
  31597. this._preActivateId = sceneRenderId;
  31598. this._visibleInstances = null;
  31599. return this;
  31600. };
  31601. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31602. if (this._visibleInstances) {
  31603. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31604. }
  31605. return this;
  31606. };
  31607. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31608. if (!this._visibleInstances) {
  31609. this._visibleInstances = {};
  31610. this._visibleInstances.defaultRenderId = renderId;
  31611. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31612. }
  31613. if (!this._visibleInstances[renderId]) {
  31614. this._visibleInstances[renderId] = new Array();
  31615. }
  31616. this._visibleInstances[renderId].push(instance);
  31617. return this;
  31618. };
  31619. /**
  31620. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31621. * This means the mesh underlying bounding box and sphere are recomputed.
  31622. * Returns the Mesh.
  31623. */
  31624. Mesh.prototype.refreshBoundingInfo = function () {
  31625. return this._refreshBoundingInfo(false);
  31626. };
  31627. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31628. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31629. return this;
  31630. }
  31631. var data = this._getPositionData(applySkeleton);
  31632. if (data) {
  31633. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31634. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31635. }
  31636. if (this.subMeshes) {
  31637. for (var index = 0; index < this.subMeshes.length; index++) {
  31638. this.subMeshes[index].refreshBoundingInfo();
  31639. }
  31640. }
  31641. this._updateBoundingInfo();
  31642. return this;
  31643. };
  31644. Mesh.prototype._getPositionData = function (applySkeleton) {
  31645. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31646. if (data && applySkeleton && this.skeleton) {
  31647. data = BABYLON.Tools.Slice(data);
  31648. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31649. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31650. if (matricesWeightsData && matricesIndicesData) {
  31651. var needExtras = this.numBoneInfluencers > 4;
  31652. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31653. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31654. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31655. var tempVector = BABYLON.Tmp.Vector3[0];
  31656. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31657. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31658. var matWeightIdx = 0;
  31659. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31660. finalMatrix.reset();
  31661. var inf;
  31662. var weight;
  31663. for (inf = 0; inf < 4; inf++) {
  31664. weight = matricesWeightsData[matWeightIdx + inf];
  31665. if (weight <= 0)
  31666. break;
  31667. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31668. finalMatrix.addToSelf(tempMatrix);
  31669. }
  31670. if (needExtras) {
  31671. for (inf = 0; inf < 4; inf++) {
  31672. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31673. if (weight <= 0)
  31674. break;
  31675. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31676. finalMatrix.addToSelf(tempMatrix);
  31677. }
  31678. }
  31679. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31680. tempVector.toArray(data, index);
  31681. }
  31682. }
  31683. }
  31684. return data;
  31685. };
  31686. Mesh.prototype._createGlobalSubMesh = function (force) {
  31687. var totalVertices = this.getTotalVertices();
  31688. if (!totalVertices || !this.getIndices()) {
  31689. return null;
  31690. }
  31691. // Check if we need to recreate the submeshes
  31692. if (this.subMeshes && this.subMeshes.length > 0) {
  31693. var ib = this.getIndices();
  31694. if (!ib) {
  31695. return null;
  31696. }
  31697. var totalIndices = ib.length;
  31698. var needToRecreate = false;
  31699. if (force) {
  31700. needToRecreate = true;
  31701. }
  31702. else {
  31703. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31704. var submesh = _a[_i];
  31705. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31706. needToRecreate = true;
  31707. break;
  31708. }
  31709. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31710. needToRecreate = true;
  31711. break;
  31712. }
  31713. }
  31714. }
  31715. if (!needToRecreate) {
  31716. return this.subMeshes[0];
  31717. }
  31718. }
  31719. this.releaseSubMeshes();
  31720. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31721. };
  31722. Mesh.prototype.subdivide = function (count) {
  31723. if (count < 1) {
  31724. return;
  31725. }
  31726. var totalIndices = this.getTotalIndices();
  31727. var subdivisionSize = (totalIndices / count) | 0;
  31728. var offset = 0;
  31729. // Ensure that subdivisionSize is a multiple of 3
  31730. while (subdivisionSize % 3 !== 0) {
  31731. subdivisionSize++;
  31732. }
  31733. this.releaseSubMeshes();
  31734. for (var index = 0; index < count; index++) {
  31735. if (offset >= totalIndices) {
  31736. break;
  31737. }
  31738. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31739. offset += subdivisionSize;
  31740. }
  31741. this.synchronizeInstances();
  31742. };
  31743. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31744. if (updatable === void 0) { updatable = false; }
  31745. if (!this._geometry) {
  31746. var vertexData = new BABYLON.VertexData();
  31747. vertexData.set(data, kind);
  31748. var scene = this.getScene();
  31749. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31750. }
  31751. else {
  31752. this._geometry.setVerticesData(kind, data, updatable, stride);
  31753. }
  31754. return this;
  31755. };
  31756. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31757. if (updatable === void 0) { updatable = true; }
  31758. var vb = this.getVertexBuffer(kind);
  31759. if (!vb || vb.isUpdatable() === updatable) {
  31760. return;
  31761. }
  31762. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31763. };
  31764. /**
  31765. * Sets the mesh VertexBuffer.
  31766. * Returns the Mesh.
  31767. */
  31768. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31769. if (!this._geometry) {
  31770. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31771. }
  31772. this._geometry.setVerticesBuffer(buffer);
  31773. return this;
  31774. };
  31775. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31776. if (!this._geometry) {
  31777. return this;
  31778. }
  31779. if (!makeItUnique) {
  31780. this._geometry.updateVerticesData(kind, data, updateExtends);
  31781. }
  31782. else {
  31783. this.makeGeometryUnique();
  31784. this.updateVerticesData(kind, data, updateExtends, false);
  31785. }
  31786. return this;
  31787. };
  31788. /**
  31789. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31790. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31791. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31792. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31793. * Returns the Mesh.
  31794. */
  31795. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31796. if (computeNormals === void 0) { computeNormals = true; }
  31797. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31798. if (!positions) {
  31799. return this;
  31800. }
  31801. positionFunction(positions);
  31802. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31803. if (computeNormals) {
  31804. var indices = this.getIndices();
  31805. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31806. if (!normals) {
  31807. return this;
  31808. }
  31809. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31810. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31811. }
  31812. return this;
  31813. };
  31814. /**
  31815. * Creates a un-shared specific occurence of the geometry for the mesh.
  31816. * Returns the Mesh.
  31817. */
  31818. Mesh.prototype.makeGeometryUnique = function () {
  31819. if (!this._geometry) {
  31820. return this;
  31821. }
  31822. var oldGeometry = this._geometry;
  31823. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31824. oldGeometry.releaseForMesh(this, true);
  31825. geometry.applyToMesh(this);
  31826. return this;
  31827. };
  31828. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31829. if (totalVertices === void 0) { totalVertices = null; }
  31830. if (updatable === void 0) { updatable = false; }
  31831. if (!this._geometry) {
  31832. var vertexData = new BABYLON.VertexData();
  31833. vertexData.indices = indices;
  31834. var scene = this.getScene();
  31835. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31836. }
  31837. else {
  31838. this._geometry.setIndices(indices, totalVertices, updatable);
  31839. }
  31840. return this;
  31841. };
  31842. /**
  31843. * Update the current index buffer
  31844. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31845. * Returns the Mesh.
  31846. */
  31847. Mesh.prototype.updateIndices = function (indices, offset) {
  31848. if (!this._geometry) {
  31849. return this;
  31850. }
  31851. this._geometry.updateIndices(indices, offset);
  31852. return this;
  31853. };
  31854. /**
  31855. * Invert the geometry to move from a right handed system to a left handed one.
  31856. * Returns the Mesh.
  31857. */
  31858. Mesh.prototype.toLeftHanded = function () {
  31859. if (!this._geometry) {
  31860. return this;
  31861. }
  31862. this._geometry.toLeftHanded();
  31863. return this;
  31864. };
  31865. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31866. if (!this._geometry) {
  31867. return this;
  31868. }
  31869. var engine = this.getScene().getEngine();
  31870. // Wireframe
  31871. var indexToBind;
  31872. if (this._unIndexed) {
  31873. indexToBind = null;
  31874. }
  31875. else {
  31876. switch (fillMode) {
  31877. case BABYLON.Material.PointFillMode:
  31878. indexToBind = null;
  31879. break;
  31880. case BABYLON.Material.WireFrameFillMode:
  31881. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31882. break;
  31883. default:
  31884. case BABYLON.Material.TriangleFillMode:
  31885. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31886. break;
  31887. }
  31888. }
  31889. // VBOs
  31890. this._geometry._bind(effect, indexToBind);
  31891. return this;
  31892. };
  31893. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31894. if (alternate === void 0) { alternate = false; }
  31895. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31896. return this;
  31897. }
  31898. this.onBeforeDrawObservable.notifyObservers(this);
  31899. var scene = this.getScene();
  31900. var engine = scene.getEngine();
  31901. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31902. // or triangles as points
  31903. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31904. }
  31905. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31906. // Triangles as wireframe
  31907. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31908. }
  31909. else {
  31910. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31911. }
  31912. if (scene._isAlternateRenderingEnabled && !alternate) {
  31913. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31914. if (!effect || !scene.activeCamera) {
  31915. return this;
  31916. }
  31917. scene._switchToAlternateCameraConfiguration(true);
  31918. this._effectiveMaterial.bindView(effect);
  31919. this._effectiveMaterial.bindViewProjection(effect);
  31920. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31921. this._draw(subMesh, fillMode, instancesCount, true);
  31922. engine.setViewport(scene.activeCamera.viewport);
  31923. scene._switchToAlternateCameraConfiguration(false);
  31924. this._effectiveMaterial.bindView(effect);
  31925. this._effectiveMaterial.bindViewProjection(effect);
  31926. }
  31927. return this;
  31928. };
  31929. /**
  31930. * Registers for this mesh a javascript function called just before the rendering process.
  31931. * This function is passed the current mesh.
  31932. * Return the Mesh.
  31933. */
  31934. Mesh.prototype.registerBeforeRender = function (func) {
  31935. this.onBeforeRenderObservable.add(func);
  31936. return this;
  31937. };
  31938. /**
  31939. * Disposes a previously registered javascript function called before the rendering.
  31940. * This function is passed the current mesh.
  31941. * Returns the Mesh.
  31942. */
  31943. Mesh.prototype.unregisterBeforeRender = function (func) {
  31944. this.onBeforeRenderObservable.removeCallback(func);
  31945. return this;
  31946. };
  31947. /**
  31948. * Registers for this mesh a javascript function called just after the rendering is complete.
  31949. * This function is passed the current mesh.
  31950. * Returns the Mesh.
  31951. */
  31952. Mesh.prototype.registerAfterRender = function (func) {
  31953. this.onAfterRenderObservable.add(func);
  31954. return this;
  31955. };
  31956. /**
  31957. * Disposes a previously registered javascript function called after the rendering.
  31958. * This function is passed the current mesh.
  31959. * Return the Mesh.
  31960. */
  31961. Mesh.prototype.unregisterAfterRender = function (func) {
  31962. this.onAfterRenderObservable.removeCallback(func);
  31963. return this;
  31964. };
  31965. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31966. var scene = this.getScene();
  31967. this._batchCache.mustReturn = false;
  31968. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31969. this._batchCache.visibleInstances[subMeshId] = null;
  31970. if (this._visibleInstances) {
  31971. var currentRenderId = scene.getRenderId();
  31972. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31973. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31974. var selfRenderId = this._renderId;
  31975. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31976. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31977. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31978. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31979. }
  31980. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31981. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31982. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31983. this._batchCache.mustReturn = true;
  31984. return this._batchCache;
  31985. }
  31986. if (currentRenderId !== selfRenderId) {
  31987. this._batchCache.renderSelf[subMeshId] = false;
  31988. }
  31989. }
  31990. this._renderIdForInstances[subMeshId] = currentRenderId;
  31991. }
  31992. return this._batchCache;
  31993. };
  31994. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31995. var visibleInstances = batch.visibleInstances[subMesh._id];
  31996. if (!visibleInstances) {
  31997. return this;
  31998. }
  31999. var matricesCount = visibleInstances.length + 1;
  32000. var bufferSize = matricesCount * 16 * 4;
  32001. var currentInstancesBufferSize = this._instancesBufferSize;
  32002. var instancesBuffer = this._instancesBuffer;
  32003. while (this._instancesBufferSize < bufferSize) {
  32004. this._instancesBufferSize *= 2;
  32005. }
  32006. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32007. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32008. }
  32009. var offset = 0;
  32010. var instancesCount = 0;
  32011. var world = this.getWorldMatrix();
  32012. if (batch.renderSelf[subMesh._id]) {
  32013. world.copyToArray(this._instancesData, offset);
  32014. offset += 16;
  32015. instancesCount++;
  32016. }
  32017. if (visibleInstances) {
  32018. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32019. var instance = visibleInstances[instanceIndex];
  32020. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32021. offset += 16;
  32022. instancesCount++;
  32023. }
  32024. }
  32025. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32026. if (instancesBuffer) {
  32027. instancesBuffer.dispose();
  32028. }
  32029. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32030. this._instancesBuffer = instancesBuffer;
  32031. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32032. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32033. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32034. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32035. }
  32036. else {
  32037. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32038. }
  32039. this._bind(subMesh, effect, fillMode);
  32040. this._draw(subMesh, fillMode, instancesCount);
  32041. engine.unbindInstanceAttributes();
  32042. return this;
  32043. };
  32044. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32045. var scene = this.getScene();
  32046. var engine = scene.getEngine();
  32047. if (hardwareInstancedRendering) {
  32048. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32049. }
  32050. else {
  32051. if (batch.renderSelf[subMesh._id]) {
  32052. // Draw
  32053. if (onBeforeDraw) {
  32054. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32055. }
  32056. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32057. }
  32058. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32059. if (visibleInstancesForSubMesh) {
  32060. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32061. var instance = visibleInstancesForSubMesh[instanceIndex];
  32062. // World
  32063. var world = instance.getWorldMatrix();
  32064. if (onBeforeDraw) {
  32065. onBeforeDraw(true, world, effectiveMaterial);
  32066. }
  32067. // Draw
  32068. this._draw(subMesh, fillMode);
  32069. }
  32070. }
  32071. }
  32072. return this;
  32073. };
  32074. /**
  32075. * Triggers the draw call for the mesh.
  32076. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32077. * Returns the Mesh.
  32078. */
  32079. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32080. this._checkOcclusionQuery();
  32081. if (this._isOccluded) {
  32082. return this;
  32083. }
  32084. var scene = this.getScene();
  32085. // Managing instances
  32086. var batch = this._getInstancesRenderList(subMesh._id);
  32087. if (batch.mustReturn) {
  32088. return this;
  32089. }
  32090. // Checking geometry state
  32091. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32092. return this;
  32093. }
  32094. this.onBeforeRenderObservable.notifyObservers(this);
  32095. var engine = scene.getEngine();
  32096. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32097. // Material
  32098. var material = subMesh.getMaterial();
  32099. if (!material) {
  32100. return this;
  32101. }
  32102. this._effectiveMaterial = material;
  32103. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32104. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32105. return this;
  32106. }
  32107. }
  32108. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32109. return this;
  32110. }
  32111. // Alpha mode
  32112. if (enableAlphaMode) {
  32113. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32114. }
  32115. // Outline - step 1
  32116. var savedDepthWrite = engine.getDepthWrite();
  32117. if (this.renderOutline) {
  32118. engine.setDepthWrite(false);
  32119. scene.getOutlineRenderer().render(subMesh, batch);
  32120. engine.setDepthWrite(savedDepthWrite);
  32121. }
  32122. var effect;
  32123. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32124. effect = subMesh.effect;
  32125. }
  32126. else {
  32127. effect = this._effectiveMaterial.getEffect();
  32128. }
  32129. if (!effect) {
  32130. return this;
  32131. }
  32132. var sideOrientation = this.overrideMaterialSideOrientation;
  32133. if (sideOrientation == null) {
  32134. sideOrientation = this._effectiveMaterial.sideOrientation;
  32135. if (this._getWorldMatrixDeterminant() < 0) {
  32136. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32137. }
  32138. }
  32139. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32140. if (this._effectiveMaterial.forceDepthWrite) {
  32141. engine.setDepthWrite(true);
  32142. }
  32143. // Bind
  32144. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32145. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32146. this._bind(subMesh, effect, fillMode);
  32147. }
  32148. var world = this.getWorldMatrix();
  32149. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32150. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32151. }
  32152. else {
  32153. this._effectiveMaterial.bind(world, this);
  32154. }
  32155. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32156. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32157. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32158. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32159. }
  32160. // Draw
  32161. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32162. // Unbind
  32163. this._effectiveMaterial.unbind();
  32164. // Outline - step 2
  32165. if (this.renderOutline && savedDepthWrite) {
  32166. engine.setDepthWrite(true);
  32167. engine.setColorWrite(false);
  32168. scene.getOutlineRenderer().render(subMesh, batch);
  32169. engine.setColorWrite(true);
  32170. }
  32171. // Overlay
  32172. if (this.renderOverlay) {
  32173. var currentMode = engine.getAlphaMode();
  32174. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32175. scene.getOutlineRenderer().render(subMesh, batch, true);
  32176. engine.setAlphaMode(currentMode);
  32177. }
  32178. this.onAfterRenderObservable.notifyObservers(this);
  32179. return this;
  32180. };
  32181. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32182. if (isInstance && effectiveMaterial) {
  32183. effectiveMaterial.bindOnlyWorldMatrix(world);
  32184. }
  32185. };
  32186. /**
  32187. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32188. */
  32189. Mesh.prototype.getEmittedParticleSystems = function () {
  32190. var results = new Array();
  32191. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32192. var particleSystem = this.getScene().particleSystems[index];
  32193. if (particleSystem.emitter === this) {
  32194. results.push(particleSystem);
  32195. }
  32196. }
  32197. return results;
  32198. };
  32199. /**
  32200. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32201. */
  32202. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32203. var results = new Array();
  32204. var descendants = this.getDescendants();
  32205. descendants.push(this);
  32206. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32207. var particleSystem = this.getScene().particleSystems[index];
  32208. var emitter = particleSystem.emitter;
  32209. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32210. results.push(particleSystem);
  32211. }
  32212. }
  32213. return results;
  32214. };
  32215. /**
  32216. * Normalize matrix weights so that all vertices have a total weight set to 1
  32217. */
  32218. Mesh.prototype.cleanMatrixWeights = function () {
  32219. var epsilon = 1e-3;
  32220. var noInfluenceBoneIndex = 0.0;
  32221. if (this.skeleton) {
  32222. noInfluenceBoneIndex = this.skeleton.bones.length;
  32223. }
  32224. else {
  32225. return;
  32226. }
  32227. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32228. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32229. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32230. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32231. var influencers = this.numBoneInfluencers;
  32232. var size = matricesWeights.length;
  32233. for (var i = 0; i < size; i += 4) {
  32234. var weight = 0.0;
  32235. var firstZeroWeight = -1;
  32236. for (var j = 0; j < 4; j++) {
  32237. var w = matricesWeights[i + j];
  32238. weight += w;
  32239. if (w < epsilon && firstZeroWeight < 0) {
  32240. firstZeroWeight = j;
  32241. }
  32242. }
  32243. if (matricesWeightsExtra) {
  32244. for (var j = 0; j < 4; j++) {
  32245. var w = matricesWeightsExtra[i + j];
  32246. weight += w;
  32247. if (w < epsilon && firstZeroWeight < 0) {
  32248. firstZeroWeight = j + 4;
  32249. }
  32250. }
  32251. }
  32252. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32253. firstZeroWeight = influencers - 1;
  32254. }
  32255. if (weight > epsilon) {
  32256. var mweight = 1.0 / weight;
  32257. for (var j = 0; j < 4; j++) {
  32258. matricesWeights[i + j] *= mweight;
  32259. }
  32260. if (matricesWeightsExtra) {
  32261. for (var j = 0; j < 4; j++) {
  32262. matricesWeightsExtra[i + j] *= mweight;
  32263. }
  32264. }
  32265. }
  32266. else {
  32267. if (firstZeroWeight >= 4) {
  32268. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32269. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32270. }
  32271. else {
  32272. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32273. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32274. }
  32275. }
  32276. }
  32277. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32278. if (matricesIndicesExtra) {
  32279. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32280. }
  32281. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32282. if (matricesWeightsExtra) {
  32283. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32284. }
  32285. };
  32286. Mesh.prototype._checkDelayState = function () {
  32287. var scene = this.getScene();
  32288. if (this._geometry) {
  32289. this._geometry.load(scene);
  32290. }
  32291. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32292. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32293. this._queueLoad(scene);
  32294. }
  32295. return this;
  32296. };
  32297. Mesh.prototype._queueLoad = function (scene) {
  32298. var _this = this;
  32299. scene._addPendingData(this);
  32300. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32301. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32302. if (data instanceof ArrayBuffer) {
  32303. _this._delayLoadingFunction(data, _this);
  32304. }
  32305. else {
  32306. _this._delayLoadingFunction(JSON.parse(data), _this);
  32307. }
  32308. _this.instances.forEach(function (instance) {
  32309. instance._syncSubMeshes();
  32310. });
  32311. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32312. scene._removePendingData(_this);
  32313. }, function () { }, scene.database, getBinaryData);
  32314. return this;
  32315. };
  32316. /**
  32317. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32318. */
  32319. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32320. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32321. return false;
  32322. }
  32323. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32324. return false;
  32325. }
  32326. this._checkDelayState();
  32327. return true;
  32328. };
  32329. /**
  32330. * Sets the mesh material by the material or multiMaterial `id` property.
  32331. * The material `id` is a string identifying the material or the multiMaterial.
  32332. * This method returns the Mesh.
  32333. */
  32334. Mesh.prototype.setMaterialByID = function (id) {
  32335. var materials = this.getScene().materials;
  32336. var index;
  32337. for (index = materials.length - 1; index > -1; index--) {
  32338. if (materials[index].id === id) {
  32339. this.material = materials[index];
  32340. return this;
  32341. }
  32342. }
  32343. // Multi
  32344. var multiMaterials = this.getScene().multiMaterials;
  32345. for (index = multiMaterials.length - 1; index > -1; index--) {
  32346. if (multiMaterials[index].id === id) {
  32347. this.material = multiMaterials[index];
  32348. return this;
  32349. }
  32350. }
  32351. return this;
  32352. };
  32353. /**
  32354. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32355. */
  32356. Mesh.prototype.getAnimatables = function () {
  32357. var results = new Array();
  32358. if (this.material) {
  32359. results.push(this.material);
  32360. }
  32361. if (this.skeleton) {
  32362. results.push(this.skeleton);
  32363. }
  32364. return results;
  32365. };
  32366. /**
  32367. * Modifies the mesh geometry according to the passed transformation matrix.
  32368. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32369. * The mesh normals are modified accordingly the same transformation.
  32370. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32371. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32372. * Returns the Mesh.
  32373. */
  32374. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32375. // Position
  32376. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32377. return this;
  32378. }
  32379. var submeshes = this.subMeshes.splice(0);
  32380. this._resetPointsArrayCache();
  32381. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32382. var temp = new Array();
  32383. var index;
  32384. for (index = 0; index < data.length; index += 3) {
  32385. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32386. }
  32387. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32388. // Normals
  32389. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32390. return this;
  32391. }
  32392. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32393. temp = [];
  32394. for (index = 0; index < data.length; index += 3) {
  32395. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32396. }
  32397. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32398. // flip faces?
  32399. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32400. this.flipFaces();
  32401. }
  32402. // Restore submeshes
  32403. this.releaseSubMeshes();
  32404. this.subMeshes = submeshes;
  32405. return this;
  32406. };
  32407. /**
  32408. * Modifies the mesh geometry according to its own current World Matrix.
  32409. * The mesh World Matrix is then reset.
  32410. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32411. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32412. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32413. * Returns the Mesh.
  32414. */
  32415. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32416. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32417. this.scaling.copyFromFloats(1, 1, 1);
  32418. this.position.copyFromFloats(0, 0, 0);
  32419. this.rotation.copyFromFloats(0, 0, 0);
  32420. //only if quaternion is already set
  32421. if (this.rotationQuaternion) {
  32422. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32423. }
  32424. this._worldMatrix = BABYLON.Matrix.Identity();
  32425. return this;
  32426. };
  32427. Object.defineProperty(Mesh.prototype, "_positions", {
  32428. // Cache
  32429. get: function () {
  32430. if (this._geometry) {
  32431. return this._geometry._positions;
  32432. }
  32433. return null;
  32434. },
  32435. enumerable: true,
  32436. configurable: true
  32437. });
  32438. Mesh.prototype._resetPointsArrayCache = function () {
  32439. if (this._geometry) {
  32440. this._geometry._resetPointsArrayCache();
  32441. }
  32442. return this;
  32443. };
  32444. Mesh.prototype._generatePointsArray = function () {
  32445. if (this._geometry) {
  32446. return this._geometry._generatePointsArray();
  32447. }
  32448. return false;
  32449. };
  32450. /**
  32451. * Returns a new Mesh object generated from the current mesh properties.
  32452. * This method must not get confused with createInstance().
  32453. * The parameter `name` is a string, the name given to the new mesh.
  32454. * The optional parameter `newParent` can be any Node object (default `null`).
  32455. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32456. * 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.
  32457. */
  32458. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32459. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32460. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32461. };
  32462. /**
  32463. * Releases resources associated with this mesh.
  32464. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32465. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32466. */
  32467. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32468. var _this = this;
  32469. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32470. this.morphTargetManager = null;
  32471. if (this._geometry) {
  32472. this._geometry.releaseForMesh(this, true);
  32473. }
  32474. // Sources
  32475. var meshes = this.getScene().meshes;
  32476. meshes.forEach(function (abstractMesh) {
  32477. var mesh = abstractMesh;
  32478. if (mesh._source && mesh._source === _this) {
  32479. mesh._source = null;
  32480. }
  32481. });
  32482. this._source = null;
  32483. // Instances
  32484. if (this._instancesBuffer) {
  32485. this._instancesBuffer.dispose();
  32486. this._instancesBuffer = null;
  32487. }
  32488. while (this.instances.length) {
  32489. this.instances[0].dispose();
  32490. }
  32491. // Effect layers.
  32492. var effectLayers = this.getScene().effectLayers;
  32493. for (var i = 0; i < effectLayers.length; i++) {
  32494. var effectLayer = effectLayers[i];
  32495. if (effectLayer) {
  32496. effectLayer._disposeMesh(this);
  32497. }
  32498. }
  32499. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32500. };
  32501. /**
  32502. * Modifies the mesh geometry according to a displacement map.
  32503. * 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.
  32504. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32505. * This method returns nothing.
  32506. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32507. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32508. * 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.
  32509. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32510. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32511. *
  32512. * Returns the Mesh.
  32513. */
  32514. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32515. var _this = this;
  32516. var scene = this.getScene();
  32517. var onload = function (img) {
  32518. // Getting height map data
  32519. var canvas = document.createElement("canvas");
  32520. var context = canvas.getContext("2d");
  32521. var heightMapWidth = img.width;
  32522. var heightMapHeight = img.height;
  32523. canvas.width = heightMapWidth;
  32524. canvas.height = heightMapHeight;
  32525. context.drawImage(img, 0, 0);
  32526. // Create VertexData from map data
  32527. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32528. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32529. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32530. //execute success callback, if set
  32531. if (onSuccess) {
  32532. onSuccess(_this);
  32533. }
  32534. };
  32535. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32536. return this;
  32537. };
  32538. /**
  32539. * Modifies the mesh geometry according to a displacementMap buffer.
  32540. * 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.
  32541. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32542. * This method returns nothing.
  32543. * 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.
  32544. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32545. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32546. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32547. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32548. *
  32549. * Returns the Mesh.
  32550. */
  32551. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32552. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32553. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32554. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32555. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32556. return this;
  32557. }
  32558. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32559. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32560. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32561. var position = BABYLON.Vector3.Zero();
  32562. var normal = BABYLON.Vector3.Zero();
  32563. var uv = BABYLON.Vector2.Zero();
  32564. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32565. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32566. for (var index = 0; index < positions.length; index += 3) {
  32567. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32568. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32569. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32570. // Compute height
  32571. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32572. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32573. var pos = (u + v * heightMapWidth) * 4;
  32574. var r = buffer[pos] / 255.0;
  32575. var g = buffer[pos + 1] / 255.0;
  32576. var b = buffer[pos + 2] / 255.0;
  32577. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32578. normal.normalize();
  32579. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32580. position = position.add(normal);
  32581. position.toArray(positions, index);
  32582. }
  32583. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32584. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32585. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32586. return this;
  32587. };
  32588. /**
  32589. * Modify the mesh to get a flat shading rendering.
  32590. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32591. * This method returns the Mesh.
  32592. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32593. */
  32594. Mesh.prototype.convertToFlatShadedMesh = function () {
  32595. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32596. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32597. var kinds = this.getVerticesDataKinds();
  32598. var vbs = {};
  32599. var data = {};
  32600. var newdata = {};
  32601. var updatableNormals = false;
  32602. var kindIndex;
  32603. var kind;
  32604. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32605. kind = kinds[kindIndex];
  32606. var vertexBuffer = this.getVertexBuffer(kind);
  32607. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32608. updatableNormals = vertexBuffer.isUpdatable();
  32609. kinds.splice(kindIndex, 1);
  32610. kindIndex--;
  32611. continue;
  32612. }
  32613. vbs[kind] = vertexBuffer;
  32614. data[kind] = vbs[kind].getData();
  32615. newdata[kind] = [];
  32616. }
  32617. // Save previous submeshes
  32618. var previousSubmeshes = this.subMeshes.slice(0);
  32619. var indices = this.getIndices();
  32620. var totalIndices = this.getTotalIndices();
  32621. // Generating unique vertices per face
  32622. var index;
  32623. for (index = 0; index < totalIndices; index++) {
  32624. var vertexIndex = indices[index];
  32625. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32626. kind = kinds[kindIndex];
  32627. var stride = vbs[kind].getStrideSize();
  32628. for (var offset = 0; offset < stride; offset++) {
  32629. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32630. }
  32631. }
  32632. }
  32633. // Updating faces & normal
  32634. var normals = [];
  32635. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32636. for (index = 0; index < totalIndices; index += 3) {
  32637. indices[index] = index;
  32638. indices[index + 1] = index + 1;
  32639. indices[index + 2] = index + 2;
  32640. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32641. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32642. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32643. var p1p2 = p1.subtract(p2);
  32644. var p3p2 = p3.subtract(p2);
  32645. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32646. // Store same normals for every vertex
  32647. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32648. normals.push(normal.x);
  32649. normals.push(normal.y);
  32650. normals.push(normal.z);
  32651. }
  32652. }
  32653. this.setIndices(indices);
  32654. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32655. // Updating vertex buffers
  32656. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32657. kind = kinds[kindIndex];
  32658. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32659. }
  32660. // Updating submeshes
  32661. this.releaseSubMeshes();
  32662. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32663. var previousOne = previousSubmeshes[submeshIndex];
  32664. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32665. }
  32666. this.synchronizeInstances();
  32667. return this;
  32668. };
  32669. /**
  32670. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32671. * In other words, more vertices, no more indices and a single bigger VBO.
  32672. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32673. * Returns the Mesh.
  32674. */
  32675. Mesh.prototype.convertToUnIndexedMesh = function () {
  32676. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32677. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32678. var kinds = this.getVerticesDataKinds();
  32679. var vbs = {};
  32680. var data = {};
  32681. var newdata = {};
  32682. var kindIndex;
  32683. var kind;
  32684. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32685. kind = kinds[kindIndex];
  32686. var vertexBuffer = this.getVertexBuffer(kind);
  32687. vbs[kind] = vertexBuffer;
  32688. data[kind] = vbs[kind].getData();
  32689. newdata[kind] = [];
  32690. }
  32691. // Save previous submeshes
  32692. var previousSubmeshes = this.subMeshes.slice(0);
  32693. var indices = this.getIndices();
  32694. var totalIndices = this.getTotalIndices();
  32695. // Generating unique vertices per face
  32696. var index;
  32697. for (index = 0; index < totalIndices; index++) {
  32698. var vertexIndex = indices[index];
  32699. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32700. kind = kinds[kindIndex];
  32701. var stride = vbs[kind].getStrideSize();
  32702. for (var offset = 0; offset < stride; offset++) {
  32703. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32704. }
  32705. }
  32706. }
  32707. // Updating indices
  32708. for (index = 0; index < totalIndices; index += 3) {
  32709. indices[index] = index;
  32710. indices[index + 1] = index + 1;
  32711. indices[index + 2] = index + 2;
  32712. }
  32713. this.setIndices(indices);
  32714. // Updating vertex buffers
  32715. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32716. kind = kinds[kindIndex];
  32717. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32718. }
  32719. // Updating submeshes
  32720. this.releaseSubMeshes();
  32721. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32722. var previousOne = previousSubmeshes[submeshIndex];
  32723. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32724. }
  32725. this._unIndexed = true;
  32726. this.synchronizeInstances();
  32727. return this;
  32728. };
  32729. /**
  32730. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32731. * This method returns the Mesh.
  32732. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32733. */
  32734. Mesh.prototype.flipFaces = function (flipNormals) {
  32735. if (flipNormals === void 0) { flipNormals = false; }
  32736. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32737. var i;
  32738. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32739. for (i = 0; i < vertex_data.normals.length; i++) {
  32740. vertex_data.normals[i] *= -1;
  32741. }
  32742. }
  32743. if (vertex_data.indices) {
  32744. var temp;
  32745. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32746. // reassign indices
  32747. temp = vertex_data.indices[i + 1];
  32748. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32749. vertex_data.indices[i + 2] = temp;
  32750. }
  32751. }
  32752. vertex_data.applyToMesh(this);
  32753. return this;
  32754. };
  32755. // Instances
  32756. /**
  32757. * Creates a new InstancedMesh object from the mesh model.
  32758. * An instance shares the same properties and the same material than its model.
  32759. * Only these properties of each instance can then be set individually :
  32760. * - position
  32761. * - rotation
  32762. * - rotationQuaternion
  32763. * - setPivotMatrix
  32764. * - scaling
  32765. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32766. * Warning : this method is not supported for Line mesh and LineSystem
  32767. */
  32768. Mesh.prototype.createInstance = function (name) {
  32769. return new BABYLON.InstancedMesh(name, this);
  32770. };
  32771. /**
  32772. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32773. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32774. * This method returns the Mesh.
  32775. */
  32776. Mesh.prototype.synchronizeInstances = function () {
  32777. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32778. var instance = this.instances[instanceIndex];
  32779. instance._syncSubMeshes();
  32780. }
  32781. return this;
  32782. };
  32783. /**
  32784. * Simplify the mesh according to the given array of settings.
  32785. * Function will return immediately and will simplify async. It returns the Mesh.
  32786. * @param settings a collection of simplification settings.
  32787. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32788. * @param type the type of simplification to run.
  32789. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32790. */
  32791. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32792. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32793. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32794. this.getScene().simplificationQueue.addTask({
  32795. settings: settings,
  32796. parallelProcessing: parallelProcessing,
  32797. mesh: this,
  32798. simplificationType: simplificationType,
  32799. successCallback: successCallback
  32800. });
  32801. return this;
  32802. };
  32803. /**
  32804. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32805. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32806. * This should be used together with the simplification to avoid disappearing triangles.
  32807. * Returns the Mesh.
  32808. * @param successCallback an optional success callback to be called after the optimization finished.
  32809. */
  32810. Mesh.prototype.optimizeIndices = function (successCallback) {
  32811. var _this = this;
  32812. var indices = this.getIndices();
  32813. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32814. if (!positions || !indices) {
  32815. return this;
  32816. }
  32817. var vectorPositions = new Array();
  32818. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32819. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32820. }
  32821. var dupes = new Array();
  32822. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32823. var realPos = vectorPositions.length - 1 - iteration;
  32824. var testedPosition = vectorPositions[realPos];
  32825. for (var j = 0; j < realPos; ++j) {
  32826. var againstPosition = vectorPositions[j];
  32827. if (testedPosition.equals(againstPosition)) {
  32828. dupes[realPos] = j;
  32829. break;
  32830. }
  32831. }
  32832. }, function () {
  32833. for (var i = 0; i < indices.length; ++i) {
  32834. indices[i] = dupes[indices[i]] || indices[i];
  32835. }
  32836. //indices are now reordered
  32837. var originalSubMeshes = _this.subMeshes.slice(0);
  32838. _this.setIndices(indices);
  32839. _this.subMeshes = originalSubMeshes;
  32840. if (successCallback) {
  32841. successCallback(_this);
  32842. }
  32843. });
  32844. return this;
  32845. };
  32846. Mesh.prototype.serialize = function (serializationObject) {
  32847. serializationObject.name = this.name;
  32848. serializationObject.id = this.id;
  32849. serializationObject.type = this.getClassName();
  32850. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32851. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32852. }
  32853. serializationObject.position = this.position.asArray();
  32854. if (this.rotationQuaternion) {
  32855. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32856. }
  32857. else if (this.rotation) {
  32858. serializationObject.rotation = this.rotation.asArray();
  32859. }
  32860. serializationObject.scaling = this.scaling.asArray();
  32861. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32862. serializationObject.isEnabled = this.isEnabled(false);
  32863. serializationObject.isVisible = this.isVisible;
  32864. serializationObject.infiniteDistance = this.infiniteDistance;
  32865. serializationObject.pickable = this.isPickable;
  32866. serializationObject.receiveShadows = this.receiveShadows;
  32867. serializationObject.billboardMode = this.billboardMode;
  32868. serializationObject.visibility = this.visibility;
  32869. serializationObject.checkCollisions = this.checkCollisions;
  32870. serializationObject.isBlocker = this.isBlocker;
  32871. // Parent
  32872. if (this.parent) {
  32873. serializationObject.parentId = this.parent.id;
  32874. }
  32875. // Geometry
  32876. serializationObject.isUnIndexed = this.isUnIndexed;
  32877. var geometry = this._geometry;
  32878. if (geometry) {
  32879. var geometryId = geometry.id;
  32880. serializationObject.geometryId = geometryId;
  32881. // SubMeshes
  32882. serializationObject.subMeshes = [];
  32883. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32884. var subMesh = this.subMeshes[subIndex];
  32885. serializationObject.subMeshes.push({
  32886. materialIndex: subMesh.materialIndex,
  32887. verticesStart: subMesh.verticesStart,
  32888. verticesCount: subMesh.verticesCount,
  32889. indexStart: subMesh.indexStart,
  32890. indexCount: subMesh.indexCount
  32891. });
  32892. }
  32893. }
  32894. // Material
  32895. if (this.material) {
  32896. serializationObject.materialId = this.material.id;
  32897. }
  32898. else {
  32899. this.material = null;
  32900. }
  32901. // Morph targets
  32902. if (this.morphTargetManager) {
  32903. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32904. }
  32905. // Skeleton
  32906. if (this.skeleton) {
  32907. serializationObject.skeletonId = this.skeleton.id;
  32908. }
  32909. // Physics
  32910. //TODO implement correct serialization for physics impostors.
  32911. var impostor = this.getPhysicsImpostor();
  32912. if (impostor) {
  32913. serializationObject.physicsMass = impostor.getParam("mass");
  32914. serializationObject.physicsFriction = impostor.getParam("friction");
  32915. serializationObject.physicsRestitution = impostor.getParam("mass");
  32916. serializationObject.physicsImpostor = impostor.type;
  32917. }
  32918. // Metadata
  32919. if (this.metadata) {
  32920. serializationObject.metadata = this.metadata;
  32921. }
  32922. // Instances
  32923. serializationObject.instances = [];
  32924. for (var index = 0; index < this.instances.length; index++) {
  32925. var instance = this.instances[index];
  32926. var serializationInstance = {
  32927. name: instance.name,
  32928. id: instance.id,
  32929. position: instance.position.asArray(),
  32930. scaling: instance.scaling.asArray()
  32931. };
  32932. if (instance.rotationQuaternion) {
  32933. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32934. }
  32935. else if (instance.rotation) {
  32936. serializationInstance.rotation = instance.rotation.asArray();
  32937. }
  32938. serializationObject.instances.push(serializationInstance);
  32939. // Animations
  32940. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32941. serializationInstance.ranges = instance.serializeAnimationRanges();
  32942. }
  32943. //
  32944. // Animations
  32945. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32946. serializationObject.ranges = this.serializeAnimationRanges();
  32947. // Layer mask
  32948. serializationObject.layerMask = this.layerMask;
  32949. // Alpha
  32950. serializationObject.alphaIndex = this.alphaIndex;
  32951. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32952. // Overlay
  32953. serializationObject.overlayAlpha = this.overlayAlpha;
  32954. serializationObject.overlayColor = this.overlayColor.asArray();
  32955. serializationObject.renderOverlay = this.renderOverlay;
  32956. // Fog
  32957. serializationObject.applyFog = this.applyFog;
  32958. // Action Manager
  32959. if (this.actionManager) {
  32960. serializationObject.actions = this.actionManager.serialize(this.name);
  32961. }
  32962. };
  32963. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32964. if (!this.geometry) {
  32965. return;
  32966. }
  32967. this._markSubMeshesAsAttributesDirty();
  32968. var morphTargetManager = this._morphTargetManager;
  32969. if (morphTargetManager && morphTargetManager.vertexCount) {
  32970. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32971. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32972. this.morphTargetManager = null;
  32973. return;
  32974. }
  32975. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32976. var morphTarget = morphTargetManager.getActiveTarget(index);
  32977. var positions = morphTarget.getPositions();
  32978. if (!positions) {
  32979. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32980. return;
  32981. }
  32982. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32983. var normals = morphTarget.getNormals();
  32984. if (normals) {
  32985. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32986. }
  32987. var tangents = morphTarget.getTangents();
  32988. if (tangents) {
  32989. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32990. }
  32991. }
  32992. }
  32993. else {
  32994. var index = 0;
  32995. // Positions
  32996. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32997. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32998. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32999. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33000. }
  33001. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33002. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33003. }
  33004. index++;
  33005. }
  33006. }
  33007. };
  33008. // Statics
  33009. /**
  33010. * Returns a new Mesh object parsed from the source provided.
  33011. * The parameter `parsedMesh` is the source.
  33012. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33013. */
  33014. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33015. var mesh;
  33016. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33017. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33018. }
  33019. else {
  33020. mesh = new Mesh(parsedMesh.name, scene);
  33021. }
  33022. mesh.id = parsedMesh.id;
  33023. if (BABYLON.Tags) {
  33024. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33025. }
  33026. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33027. if (parsedMesh.metadata !== undefined) {
  33028. mesh.metadata = parsedMesh.metadata;
  33029. }
  33030. if (parsedMesh.rotationQuaternion) {
  33031. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33032. }
  33033. else if (parsedMesh.rotation) {
  33034. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33035. }
  33036. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33037. if (parsedMesh.localMatrix) {
  33038. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33039. }
  33040. else if (parsedMesh.pivotMatrix) {
  33041. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33042. }
  33043. mesh.setEnabled(parsedMesh.isEnabled);
  33044. mesh.isVisible = parsedMesh.isVisible;
  33045. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33046. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33047. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33048. if (parsedMesh.applyFog !== undefined) {
  33049. mesh.applyFog = parsedMesh.applyFog;
  33050. }
  33051. if (parsedMesh.pickable !== undefined) {
  33052. mesh.isPickable = parsedMesh.pickable;
  33053. }
  33054. if (parsedMesh.alphaIndex !== undefined) {
  33055. mesh.alphaIndex = parsedMesh.alphaIndex;
  33056. }
  33057. mesh.receiveShadows = parsedMesh.receiveShadows;
  33058. mesh.billboardMode = parsedMesh.billboardMode;
  33059. if (parsedMesh.visibility !== undefined) {
  33060. mesh.visibility = parsedMesh.visibility;
  33061. }
  33062. mesh.checkCollisions = parsedMesh.checkCollisions;
  33063. if (parsedMesh.isBlocker !== undefined) {
  33064. mesh.isBlocker = parsedMesh.isBlocker;
  33065. }
  33066. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33067. // freezeWorldMatrix
  33068. if (parsedMesh.freezeWorldMatrix) {
  33069. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33070. }
  33071. // Parent
  33072. if (parsedMesh.parentId) {
  33073. mesh._waitingParentId = parsedMesh.parentId;
  33074. }
  33075. // Actions
  33076. if (parsedMesh.actions !== undefined) {
  33077. mesh._waitingActions = parsedMesh.actions;
  33078. }
  33079. // Overlay
  33080. if (parsedMesh.overlayAlpha !== undefined) {
  33081. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33082. }
  33083. if (parsedMesh.overlayColor !== undefined) {
  33084. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33085. }
  33086. if (parsedMesh.renderOverlay !== undefined) {
  33087. mesh.renderOverlay = parsedMesh.renderOverlay;
  33088. }
  33089. // Geometry
  33090. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33091. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33092. if (parsedMesh.delayLoadingFile) {
  33093. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33094. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33095. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33096. if (parsedMesh._binaryInfo) {
  33097. mesh._binaryInfo = parsedMesh._binaryInfo;
  33098. }
  33099. mesh._delayInfo = [];
  33100. if (parsedMesh.hasUVs) {
  33101. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33102. }
  33103. if (parsedMesh.hasUVs2) {
  33104. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33105. }
  33106. if (parsedMesh.hasUVs3) {
  33107. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33108. }
  33109. if (parsedMesh.hasUVs4) {
  33110. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33111. }
  33112. if (parsedMesh.hasUVs5) {
  33113. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33114. }
  33115. if (parsedMesh.hasUVs6) {
  33116. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33117. }
  33118. if (parsedMesh.hasColors) {
  33119. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33120. }
  33121. if (parsedMesh.hasMatricesIndices) {
  33122. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33123. }
  33124. if (parsedMesh.hasMatricesWeights) {
  33125. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33126. }
  33127. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33128. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33129. mesh._checkDelayState();
  33130. }
  33131. }
  33132. else {
  33133. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33134. }
  33135. // Material
  33136. if (parsedMesh.materialId) {
  33137. mesh.setMaterialByID(parsedMesh.materialId);
  33138. }
  33139. else {
  33140. mesh.material = null;
  33141. }
  33142. // Morph targets
  33143. if (parsedMesh.morphTargetManagerId > -1) {
  33144. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33145. }
  33146. // Skeleton
  33147. if (parsedMesh.skeletonId > -1) {
  33148. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33149. if (parsedMesh.numBoneInfluencers) {
  33150. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33151. }
  33152. }
  33153. // Animations
  33154. if (parsedMesh.animations) {
  33155. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33156. var parsedAnimation = parsedMesh.animations[animationIndex];
  33157. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33158. }
  33159. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33160. }
  33161. if (parsedMesh.autoAnimate) {
  33162. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33163. }
  33164. // Layer Mask
  33165. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33166. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33167. }
  33168. else {
  33169. mesh.layerMask = 0x0FFFFFFF;
  33170. }
  33171. // Physics
  33172. if (parsedMesh.physicsImpostor) {
  33173. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33174. mass: parsedMesh.physicsMass,
  33175. friction: parsedMesh.physicsFriction,
  33176. restitution: parsedMesh.physicsRestitution
  33177. }, scene);
  33178. }
  33179. // Instances
  33180. if (parsedMesh.instances) {
  33181. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33182. var parsedInstance = parsedMesh.instances[index];
  33183. var instance = mesh.createInstance(parsedInstance.name);
  33184. if (parsedInstance.id) {
  33185. instance.id = parsedInstance.id;
  33186. }
  33187. if (BABYLON.Tags) {
  33188. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33189. }
  33190. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33191. if (parsedInstance.parentId) {
  33192. instance._waitingParentId = parsedInstance.parentId;
  33193. }
  33194. if (parsedInstance.rotationQuaternion) {
  33195. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33196. }
  33197. else if (parsedInstance.rotation) {
  33198. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33199. }
  33200. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33201. instance.checkCollisions = mesh.checkCollisions;
  33202. if (parsedMesh.animations) {
  33203. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33204. parsedAnimation = parsedMesh.animations[animationIndex];
  33205. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33206. }
  33207. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33208. }
  33209. }
  33210. }
  33211. return mesh;
  33212. };
  33213. /**
  33214. * Creates a ribbon mesh.
  33215. * Please consider using the same method from the MeshBuilder class instead.
  33216. * 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.
  33217. *
  33218. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33219. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33220. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33221. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33222. * 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.
  33223. * 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.
  33224. * 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
  33225. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33226. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33227. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33228. */
  33229. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33230. if (closeArray === void 0) { closeArray = false; }
  33231. if (updatable === void 0) { updatable = false; }
  33232. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33233. pathArray: pathArray,
  33234. closeArray: closeArray,
  33235. closePath: closePath,
  33236. offset: offset,
  33237. updatable: updatable,
  33238. sideOrientation: sideOrientation,
  33239. instance: instance
  33240. }, scene);
  33241. };
  33242. /**
  33243. * Creates a plane polygonal mesh. By default, this is a disc.
  33244. * Please consider using the same method from the MeshBuilder class instead.
  33245. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33246. * 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.
  33247. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33248. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33249. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33250. */
  33251. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33252. if (scene === void 0) { scene = null; }
  33253. var options = {
  33254. radius: radius,
  33255. tessellation: tessellation,
  33256. sideOrientation: sideOrientation,
  33257. updatable: updatable
  33258. };
  33259. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33260. };
  33261. /**
  33262. * Creates a box mesh.
  33263. * Please consider using the same method from the MeshBuilder class instead.
  33264. * The parameter `size` sets the size (float) of each box side (default 1).
  33265. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33266. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33267. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33268. */
  33269. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33270. if (scene === void 0) { scene = null; }
  33271. var options = {
  33272. size: size,
  33273. sideOrientation: sideOrientation,
  33274. updatable: updatable
  33275. };
  33276. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33277. };
  33278. /**
  33279. * Creates a sphere mesh.
  33280. * Please consider using the same method from the MeshBuilder class instead.
  33281. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33282. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33283. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33284. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33285. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33286. */
  33287. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33288. var options = {
  33289. segments: segments,
  33290. diameterX: diameter,
  33291. diameterY: diameter,
  33292. diameterZ: diameter,
  33293. sideOrientation: sideOrientation,
  33294. updatable: updatable
  33295. };
  33296. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33297. };
  33298. /**
  33299. * Creates a cylinder or a cone mesh.
  33300. * Please consider using the same method from the MeshBuilder class instead.
  33301. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33302. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33303. * 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.
  33304. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33305. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33306. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33307. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33308. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33309. */
  33310. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33311. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33312. if (scene !== undefined) {
  33313. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33314. updatable = scene;
  33315. }
  33316. scene = subdivisions;
  33317. subdivisions = 1;
  33318. }
  33319. var options = {
  33320. height: height,
  33321. diameterTop: diameterTop,
  33322. diameterBottom: diameterBottom,
  33323. tessellation: tessellation,
  33324. subdivisions: subdivisions,
  33325. sideOrientation: sideOrientation,
  33326. updatable: updatable
  33327. };
  33328. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33329. };
  33330. // Torus (Code from SharpDX.org)
  33331. /**
  33332. * Creates a torus mesh.
  33333. * Please consider using the same method from the MeshBuilder class instead.
  33334. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33335. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33336. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33337. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33338. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33339. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33340. */
  33341. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33342. var options = {
  33343. diameter: diameter,
  33344. thickness: thickness,
  33345. tessellation: tessellation,
  33346. sideOrientation: sideOrientation,
  33347. updatable: updatable
  33348. };
  33349. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33350. };
  33351. /**
  33352. * Creates a torus knot mesh.
  33353. * Please consider using the same method from the MeshBuilder class instead.
  33354. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33355. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33356. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33357. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33358. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33359. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33360. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33361. */
  33362. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33363. var options = {
  33364. radius: radius,
  33365. tube: tube,
  33366. radialSegments: radialSegments,
  33367. tubularSegments: tubularSegments,
  33368. p: p,
  33369. q: q,
  33370. sideOrientation: sideOrientation,
  33371. updatable: updatable
  33372. };
  33373. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33374. };
  33375. /**
  33376. * Creates a line mesh.
  33377. * Please consider using the same method from the MeshBuilder class instead.
  33378. * 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.
  33379. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33380. * The parameter `points` is an array successive Vector3.
  33381. * 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
  33382. * When updating an instance, remember that only point positions can change, not the number of points.
  33383. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33384. */
  33385. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33386. if (scene === void 0) { scene = null; }
  33387. if (updatable === void 0) { updatable = false; }
  33388. if (instance === void 0) { instance = null; }
  33389. var options = {
  33390. points: points,
  33391. updatable: updatable,
  33392. instance: instance
  33393. };
  33394. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33395. };
  33396. /**
  33397. * Creates a dashed line mesh.
  33398. * Please consider using the same method from the MeshBuilder class instead.
  33399. * 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.
  33400. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33401. * The parameter `points` is an array successive Vector3.
  33402. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33403. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33404. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33405. * 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
  33406. * When updating an instance, remember that only point positions can change, not the number of points.
  33407. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33408. */
  33409. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33410. if (scene === void 0) { scene = null; }
  33411. var options = {
  33412. points: points,
  33413. dashSize: dashSize,
  33414. gapSize: gapSize,
  33415. dashNb: dashNb,
  33416. updatable: updatable,
  33417. instance: instance
  33418. };
  33419. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33420. };
  33421. /**
  33422. * Creates a polygon mesh.
  33423. * Please consider using the same method from the MeshBuilder class instead.
  33424. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33425. * 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.
  33426. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33427. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33428. * Remember you can only change the shape positions, not their number when updating a polygon.
  33429. */
  33430. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33431. var options = {
  33432. shape: shape,
  33433. holes: holes,
  33434. updatable: updatable,
  33435. sideOrientation: sideOrientation
  33436. };
  33437. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33438. };
  33439. /**
  33440. * Creates an extruded polygon mesh, with depth in the Y direction.
  33441. * Please consider using the same method from the MeshBuilder class instead.
  33442. */
  33443. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33444. var options = {
  33445. shape: shape,
  33446. holes: holes,
  33447. depth: depth,
  33448. updatable: updatable,
  33449. sideOrientation: sideOrientation
  33450. };
  33451. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33452. };
  33453. /**
  33454. * Creates an extruded shape mesh.
  33455. * 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.
  33456. * Please consider using the same method from the MeshBuilder class instead.
  33457. *
  33458. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33459. * 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
  33460. * extruded along the Z axis.
  33461. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33462. * 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.
  33463. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33464. * 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
  33465. * 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
  33466. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33467. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33468. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33469. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33470. */
  33471. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33472. if (scene === void 0) { scene = null; }
  33473. var options = {
  33474. shape: shape,
  33475. path: path,
  33476. scale: scale,
  33477. rotation: rotation,
  33478. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33479. sideOrientation: sideOrientation,
  33480. instance: instance,
  33481. updatable: updatable
  33482. };
  33483. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33484. };
  33485. /**
  33486. * Creates an custom extruded shape mesh.
  33487. * 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.
  33488. * Please consider using the same method from the MeshBuilder class instead.
  33489. *
  33490. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33491. * 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
  33492. * extruded along the Z axis.
  33493. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33494. * 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
  33495. * and the distance of this point from the begining of the path :
  33496. * ```javascript
  33497. * var rotationFunction = function(i, distance) {
  33498. * // do things
  33499. * return rotationValue; }
  33500. * ```
  33501. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33502. * 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
  33503. * and the distance of this point from the begining of the path :
  33504. * ```javascript
  33505. * var scaleFunction = function(i, distance) {
  33506. * // do things
  33507. * return scaleValue;}
  33508. * ```
  33509. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33510. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33511. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33512. * 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
  33513. * 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
  33514. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33515. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33516. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33517. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33518. */
  33519. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33520. var options = {
  33521. shape: shape,
  33522. path: path,
  33523. scaleFunction: scaleFunction,
  33524. rotationFunction: rotationFunction,
  33525. ribbonCloseArray: ribbonCloseArray,
  33526. ribbonClosePath: ribbonClosePath,
  33527. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33528. sideOrientation: sideOrientation,
  33529. instance: instance,
  33530. updatable: updatable
  33531. };
  33532. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33533. };
  33534. /**
  33535. * Creates lathe mesh.
  33536. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33537. * Please consider using the same method from the MeshBuilder class instead.
  33538. * 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
  33539. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33540. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33541. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33542. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33543. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33544. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33545. */
  33546. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33547. var options = {
  33548. shape: shape,
  33549. radius: radius,
  33550. tessellation: tessellation,
  33551. sideOrientation: sideOrientation,
  33552. updatable: updatable
  33553. };
  33554. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33555. };
  33556. /**
  33557. * Creates a plane mesh.
  33558. * Please consider using the same method from the MeshBuilder class instead.
  33559. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33560. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33561. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  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.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33565. var options = {
  33566. size: size,
  33567. width: size,
  33568. height: size,
  33569. sideOrientation: sideOrientation,
  33570. updatable: updatable
  33571. };
  33572. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33573. };
  33574. /**
  33575. * Creates a ground mesh.
  33576. * Please consider using the same method from the MeshBuilder class instead.
  33577. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33578. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33579. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33580. */
  33581. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33582. var options = {
  33583. width: width,
  33584. height: height,
  33585. subdivisions: subdivisions,
  33586. updatable: updatable
  33587. };
  33588. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33589. };
  33590. /**
  33591. * Creates a tiled ground mesh.
  33592. * Please consider using the same method from the MeshBuilder class instead.
  33593. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33594. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33595. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33596. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33597. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33598. * numbers of subdivisions on the ground width and height of each tile.
  33599. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33600. */
  33601. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33602. var options = {
  33603. xmin: xmin,
  33604. zmin: zmin,
  33605. xmax: xmax,
  33606. zmax: zmax,
  33607. subdivisions: subdivisions,
  33608. precision: precision,
  33609. updatable: updatable
  33610. };
  33611. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33612. };
  33613. /**
  33614. * Creates a ground mesh from a height map.
  33615. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33616. * Please consider using the same method from the MeshBuilder class instead.
  33617. * The parameter `url` sets the URL of the height map image resource.
  33618. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33619. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33620. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33621. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33622. * 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).
  33623. * This function is passed the newly built mesh :
  33624. * ```javascript
  33625. * function(mesh) { // do things
  33626. * return; }
  33627. * ```
  33628. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33629. */
  33630. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33631. var options = {
  33632. width: width,
  33633. height: height,
  33634. subdivisions: subdivisions,
  33635. minHeight: minHeight,
  33636. maxHeight: maxHeight,
  33637. updatable: updatable,
  33638. onReady: onReady
  33639. };
  33640. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33641. };
  33642. /**
  33643. * Creates a tube mesh.
  33644. * 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.
  33645. * Please consider using the same method from the MeshBuilder class instead.
  33646. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33647. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33648. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33649. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33650. * 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.
  33651. * It must return a radius value (positive float) :
  33652. * ```javascript
  33653. * var radiusFunction = function(i, distance) {
  33654. * // do things
  33655. * return radius; }
  33656. * ```
  33657. * 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
  33658. * 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
  33659. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33660. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33661. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33662. */
  33663. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33664. var options = {
  33665. path: path,
  33666. radius: radius,
  33667. tessellation: tessellation,
  33668. radiusFunction: radiusFunction,
  33669. arc: 1,
  33670. cap: cap,
  33671. updatable: updatable,
  33672. sideOrientation: sideOrientation,
  33673. instance: instance
  33674. };
  33675. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33676. };
  33677. /**
  33678. * Creates a polyhedron mesh.
  33679. * Please consider using the same method from the MeshBuilder class instead.
  33680. * 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
  33681. * to choose the wanted type.
  33682. * The parameter `size` (positive float, default 1) sets the polygon size.
  33683. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33684. * 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`.
  33685. * 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
  33686. * 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)`).
  33687. * 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
  33688. * 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.
  33689. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33690. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33691. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33692. */
  33693. Mesh.CreatePolyhedron = function (name, options, scene) {
  33694. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33695. };
  33696. /**
  33697. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33698. * Please consider using the same method from the MeshBuilder class instead.
  33699. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33700. * 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`).
  33701. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33702. * 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.
  33703. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33704. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33705. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33706. */
  33707. Mesh.CreateIcoSphere = function (name, options, scene) {
  33708. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33709. };
  33710. /**
  33711. * Creates a decal mesh.
  33712. * Please consider using the same method from the MeshBuilder class instead.
  33713. * 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.
  33714. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33715. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33716. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33717. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33718. */
  33719. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33720. var options = {
  33721. position: position,
  33722. normal: normal,
  33723. size: size,
  33724. angle: angle
  33725. };
  33726. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33727. };
  33728. // Skeletons
  33729. /**
  33730. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33731. */
  33732. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33733. if (!this._sourcePositions) {
  33734. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33735. if (!source) {
  33736. return this._sourcePositions;
  33737. }
  33738. this._sourcePositions = new Float32Array(source);
  33739. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33740. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33741. }
  33742. }
  33743. return this._sourcePositions;
  33744. };
  33745. /**
  33746. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33747. */
  33748. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33749. if (!this._sourceNormals) {
  33750. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33751. if (!source) {
  33752. return this._sourceNormals;
  33753. }
  33754. this._sourceNormals = new Float32Array(source);
  33755. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33756. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33757. }
  33758. }
  33759. return this._sourceNormals;
  33760. };
  33761. /**
  33762. * Updates the vertex buffer by applying transformation from the bones.
  33763. * Returns the Mesh.
  33764. *
  33765. * @param {skeleton} skeleton to apply
  33766. */
  33767. Mesh.prototype.applySkeleton = function (skeleton) {
  33768. if (!this.geometry) {
  33769. return this;
  33770. }
  33771. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33772. return this;
  33773. }
  33774. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33775. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33776. return this;
  33777. }
  33778. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33779. return this;
  33780. }
  33781. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33782. return this;
  33783. }
  33784. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33785. return this;
  33786. }
  33787. if (!this._sourcePositions) {
  33788. var submeshes = this.subMeshes.slice();
  33789. this.setPositionsForCPUSkinning();
  33790. this.subMeshes = submeshes;
  33791. }
  33792. if (!this._sourceNormals) {
  33793. this.setNormalsForCPUSkinning();
  33794. }
  33795. // positionsData checks for not being Float32Array will only pass at most once
  33796. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33797. if (!positionsData) {
  33798. return this;
  33799. }
  33800. if (!(positionsData instanceof Float32Array)) {
  33801. positionsData = new Float32Array(positionsData);
  33802. }
  33803. // normalsData checks for not being Float32Array will only pass at most once
  33804. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33805. if (!normalsData) {
  33806. return this;
  33807. }
  33808. if (!(normalsData instanceof Float32Array)) {
  33809. normalsData = new Float32Array(normalsData);
  33810. }
  33811. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33812. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33813. if (!matricesWeightsData || !matricesIndicesData) {
  33814. return this;
  33815. }
  33816. var needExtras = this.numBoneInfluencers > 4;
  33817. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33818. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33819. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33820. var tempVector3 = BABYLON.Vector3.Zero();
  33821. var finalMatrix = new BABYLON.Matrix();
  33822. var tempMatrix = new BABYLON.Matrix();
  33823. var matWeightIdx = 0;
  33824. var inf;
  33825. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33826. var weight;
  33827. for (inf = 0; inf < 4; inf++) {
  33828. weight = matricesWeightsData[matWeightIdx + inf];
  33829. if (weight > 0) {
  33830. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33831. finalMatrix.addToSelf(tempMatrix);
  33832. }
  33833. else
  33834. break;
  33835. }
  33836. if (needExtras) {
  33837. for (inf = 0; inf < 4; inf++) {
  33838. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33839. if (weight > 0) {
  33840. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33841. finalMatrix.addToSelf(tempMatrix);
  33842. }
  33843. else
  33844. break;
  33845. }
  33846. }
  33847. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33848. tempVector3.toArray(positionsData, index);
  33849. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33850. tempVector3.toArray(normalsData, index);
  33851. finalMatrix.reset();
  33852. }
  33853. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33854. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33855. return this;
  33856. };
  33857. // Tools
  33858. /**
  33859. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33860. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33861. */
  33862. Mesh.MinMax = function (meshes) {
  33863. var minVector = null;
  33864. var maxVector = null;
  33865. meshes.forEach(function (mesh, index, array) {
  33866. var boundingInfo = mesh.getBoundingInfo();
  33867. var boundingBox = boundingInfo.boundingBox;
  33868. if (!minVector || !maxVector) {
  33869. minVector = boundingBox.minimumWorld;
  33870. maxVector = boundingBox.maximumWorld;
  33871. }
  33872. else {
  33873. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33874. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33875. }
  33876. });
  33877. if (!minVector || !maxVector) {
  33878. return {
  33879. min: BABYLON.Vector3.Zero(),
  33880. max: BABYLON.Vector3.Zero()
  33881. };
  33882. }
  33883. return {
  33884. min: minVector,
  33885. max: maxVector
  33886. };
  33887. };
  33888. /**
  33889. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33890. */
  33891. Mesh.Center = function (meshesOrMinMaxVector) {
  33892. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33893. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33894. };
  33895. /**
  33896. * Merge the array of meshes into a single mesh for performance reasons.
  33897. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33898. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33899. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33900. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33901. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33902. */
  33903. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33904. if (disposeSource === void 0) { disposeSource = true; }
  33905. var index;
  33906. if (!allow32BitsIndices) {
  33907. var totalVertices = 0;
  33908. // Counting vertices
  33909. for (index = 0; index < meshes.length; index++) {
  33910. if (meshes[index]) {
  33911. totalVertices += meshes[index].getTotalVertices();
  33912. if (totalVertices > 65536) {
  33913. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33914. return null;
  33915. }
  33916. }
  33917. }
  33918. }
  33919. // Merge
  33920. var vertexData = null;
  33921. var otherVertexData;
  33922. var indiceArray = new Array();
  33923. var source = null;
  33924. for (index = 0; index < meshes.length; index++) {
  33925. if (meshes[index]) {
  33926. meshes[index].computeWorldMatrix(true);
  33927. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33928. otherVertexData.transform(meshes[index].getWorldMatrix());
  33929. if (vertexData) {
  33930. vertexData.merge(otherVertexData);
  33931. }
  33932. else {
  33933. vertexData = otherVertexData;
  33934. source = meshes[index];
  33935. }
  33936. if (subdivideWithSubMeshes) {
  33937. indiceArray.push(meshes[index].getTotalIndices());
  33938. }
  33939. }
  33940. }
  33941. source = source;
  33942. if (!meshSubclass) {
  33943. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33944. }
  33945. vertexData.applyToMesh(meshSubclass);
  33946. // Setting properties
  33947. meshSubclass.material = source.material;
  33948. meshSubclass.checkCollisions = source.checkCollisions;
  33949. // Cleaning
  33950. if (disposeSource) {
  33951. for (index = 0; index < meshes.length; index++) {
  33952. if (meshes[index]) {
  33953. meshes[index].dispose();
  33954. }
  33955. }
  33956. }
  33957. // Subdivide
  33958. if (subdivideWithSubMeshes) {
  33959. //-- Suppresions du submesh global
  33960. meshSubclass.releaseSubMeshes();
  33961. index = 0;
  33962. var offset = 0;
  33963. //-- aplique la subdivision en fonction du tableau d'indices
  33964. while (index < indiceArray.length) {
  33965. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33966. offset += indiceArray[index];
  33967. index++;
  33968. }
  33969. }
  33970. return meshSubclass;
  33971. };
  33972. // Consts
  33973. Mesh._FRONTSIDE = 0;
  33974. Mesh._BACKSIDE = 1;
  33975. Mesh._DOUBLESIDE = 2;
  33976. Mesh._DEFAULTSIDE = 0;
  33977. Mesh._NO_CAP = 0;
  33978. Mesh._CAP_START = 1;
  33979. Mesh._CAP_END = 2;
  33980. Mesh._CAP_ALL = 3;
  33981. return Mesh;
  33982. }(BABYLON.AbstractMesh));
  33983. BABYLON.Mesh = Mesh;
  33984. })(BABYLON || (BABYLON = {}));
  33985. //# sourceMappingURL=babylon.mesh.js.map
  33986. var BABYLON;
  33987. (function (BABYLON) {
  33988. var BaseSubMesh = /** @class */ (function () {
  33989. function BaseSubMesh() {
  33990. }
  33991. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33992. get: function () {
  33993. return this._materialEffect;
  33994. },
  33995. enumerable: true,
  33996. configurable: true
  33997. });
  33998. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33999. if (defines === void 0) { defines = null; }
  34000. if (this._materialEffect === effect) {
  34001. if (!effect) {
  34002. this._materialDefines = null;
  34003. }
  34004. return;
  34005. }
  34006. this._materialDefines = defines;
  34007. this._materialEffect = effect;
  34008. };
  34009. return BaseSubMesh;
  34010. }());
  34011. BABYLON.BaseSubMesh = BaseSubMesh;
  34012. var SubMesh = /** @class */ (function (_super) {
  34013. __extends(SubMesh, _super);
  34014. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34015. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34016. var _this = _super.call(this) || this;
  34017. _this.materialIndex = materialIndex;
  34018. _this.verticesStart = verticesStart;
  34019. _this.verticesCount = verticesCount;
  34020. _this.indexStart = indexStart;
  34021. _this.indexCount = indexCount;
  34022. _this._renderId = 0;
  34023. _this._mesh = mesh;
  34024. _this._renderingMesh = renderingMesh || mesh;
  34025. mesh.subMeshes.push(_this);
  34026. _this._trianglePlanes = [];
  34027. _this._id = mesh.subMeshes.length - 1;
  34028. if (createBoundingBox) {
  34029. _this.refreshBoundingInfo();
  34030. mesh.computeWorldMatrix(true);
  34031. }
  34032. return _this;
  34033. }
  34034. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34035. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34036. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34037. };
  34038. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34039. get: function () {
  34040. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34041. },
  34042. enumerable: true,
  34043. configurable: true
  34044. });
  34045. /**
  34046. * Returns the submesh BoudingInfo object.
  34047. */
  34048. SubMesh.prototype.getBoundingInfo = function () {
  34049. if (this.IsGlobal) {
  34050. return this._mesh.getBoundingInfo();
  34051. }
  34052. return this._boundingInfo;
  34053. };
  34054. /**
  34055. * Sets the submesh BoundingInfo.
  34056. * Return the SubMesh.
  34057. */
  34058. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34059. this._boundingInfo = boundingInfo;
  34060. return this;
  34061. };
  34062. /**
  34063. * Returns the mesh of the current submesh.
  34064. */
  34065. SubMesh.prototype.getMesh = function () {
  34066. return this._mesh;
  34067. };
  34068. /**
  34069. * Returns the rendering mesh of the submesh.
  34070. */
  34071. SubMesh.prototype.getRenderingMesh = function () {
  34072. return this._renderingMesh;
  34073. };
  34074. /**
  34075. * Returns the submesh material.
  34076. */
  34077. SubMesh.prototype.getMaterial = function () {
  34078. var rootMaterial = this._renderingMesh.material;
  34079. if (rootMaterial === null || rootMaterial === undefined) {
  34080. return this._mesh.getScene().defaultMaterial;
  34081. }
  34082. else if (rootMaterial.getSubMaterial) {
  34083. var multiMaterial = rootMaterial;
  34084. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34085. if (this._currentMaterial !== effectiveMaterial) {
  34086. this._currentMaterial = effectiveMaterial;
  34087. this._materialDefines = null;
  34088. }
  34089. return effectiveMaterial;
  34090. }
  34091. return rootMaterial;
  34092. };
  34093. // Methods
  34094. /**
  34095. * Sets a new updated BoundingInfo object to the submesh.
  34096. * Returns the SubMesh.
  34097. */
  34098. SubMesh.prototype.refreshBoundingInfo = function () {
  34099. this._lastColliderWorldVertices = null;
  34100. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34101. return this;
  34102. }
  34103. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34104. if (!data) {
  34105. this._boundingInfo = this._mesh.getBoundingInfo();
  34106. return this;
  34107. }
  34108. var indices = this._renderingMesh.getIndices();
  34109. var extend;
  34110. //is this the only submesh?
  34111. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34112. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34113. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34114. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34115. }
  34116. else {
  34117. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34118. }
  34119. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34120. return this;
  34121. };
  34122. SubMesh.prototype._checkCollision = function (collider) {
  34123. var boundingInfo = this.getBoundingInfo();
  34124. return boundingInfo._checkCollision(collider);
  34125. };
  34126. /**
  34127. * Updates the submesh BoundingInfo.
  34128. * Returns the Submesh.
  34129. */
  34130. SubMesh.prototype.updateBoundingInfo = function (world) {
  34131. var boundingInfo = this.getBoundingInfo();
  34132. if (!boundingInfo) {
  34133. this.refreshBoundingInfo();
  34134. boundingInfo = this.getBoundingInfo();
  34135. }
  34136. boundingInfo.update(world);
  34137. return this;
  34138. };
  34139. /**
  34140. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34141. * Boolean returned.
  34142. */
  34143. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34144. var boundingInfo = this.getBoundingInfo();
  34145. if (!boundingInfo) {
  34146. return false;
  34147. }
  34148. return boundingInfo.isInFrustum(frustumPlanes);
  34149. };
  34150. /**
  34151. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34152. * Boolean returned.
  34153. */
  34154. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34155. var boundingInfo = this.getBoundingInfo();
  34156. if (!boundingInfo) {
  34157. return false;
  34158. }
  34159. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34160. };
  34161. /**
  34162. * Renders the submesh.
  34163. * Returns it.
  34164. */
  34165. SubMesh.prototype.render = function (enableAlphaMode) {
  34166. this._renderingMesh.render(this, enableAlphaMode);
  34167. return this;
  34168. };
  34169. /**
  34170. * Returns a new Index Buffer.
  34171. * Type returned : WebGLBuffer.
  34172. */
  34173. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34174. if (!this._linesIndexBuffer) {
  34175. var linesIndices = [];
  34176. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34177. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34178. }
  34179. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34180. this.linesIndexCount = linesIndices.length;
  34181. }
  34182. return this._linesIndexBuffer;
  34183. };
  34184. /**
  34185. * True is the passed Ray intersects the submesh bounding box.
  34186. * Boolean returned.
  34187. */
  34188. SubMesh.prototype.canIntersects = function (ray) {
  34189. var boundingInfo = this.getBoundingInfo();
  34190. if (!boundingInfo) {
  34191. return false;
  34192. }
  34193. return ray.intersectsBox(boundingInfo.boundingBox);
  34194. };
  34195. /**
  34196. * Returns an object IntersectionInfo.
  34197. */
  34198. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34199. var intersectInfo = null;
  34200. var material = this.getMaterial();
  34201. if (!material) {
  34202. return null;
  34203. }
  34204. switch (material.fillMode) {
  34205. case BABYLON.Material.PointListDrawMode:
  34206. case BABYLON.Material.LineListDrawMode:
  34207. case BABYLON.Material.LineLoopDrawMode:
  34208. case BABYLON.Material.LineStripDrawMode:
  34209. case BABYLON.Material.TriangleFanDrawMode:
  34210. case BABYLON.Material.TriangleStripDrawMode:
  34211. return null;
  34212. }
  34213. // LineMesh first as it's also a Mesh...
  34214. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34215. var lineMesh = this._mesh;
  34216. // Line test
  34217. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34218. var p0 = positions[indices[index]];
  34219. var p1 = positions[indices[index + 1]];
  34220. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34221. if (length < 0) {
  34222. continue;
  34223. }
  34224. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34225. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34226. if (fastCheck) {
  34227. break;
  34228. }
  34229. }
  34230. }
  34231. }
  34232. else {
  34233. // Triangles test
  34234. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34235. var p0 = positions[indices[index]];
  34236. var p1 = positions[indices[index + 1]];
  34237. var p2 = positions[indices[index + 2]];
  34238. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34239. if (currentIntersectInfo) {
  34240. if (currentIntersectInfo.distance < 0) {
  34241. continue;
  34242. }
  34243. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34244. intersectInfo = currentIntersectInfo;
  34245. intersectInfo.faceId = index / 3;
  34246. if (fastCheck) {
  34247. break;
  34248. }
  34249. }
  34250. }
  34251. }
  34252. }
  34253. return intersectInfo;
  34254. };
  34255. SubMesh.prototype._rebuild = function () {
  34256. if (this._linesIndexBuffer) {
  34257. this._linesIndexBuffer = null;
  34258. }
  34259. };
  34260. // Clone
  34261. /**
  34262. * Creates a new Submesh from the passed Mesh.
  34263. */
  34264. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34265. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34266. if (!this.IsGlobal) {
  34267. var boundingInfo = this.getBoundingInfo();
  34268. if (!boundingInfo) {
  34269. return result;
  34270. }
  34271. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34272. }
  34273. return result;
  34274. };
  34275. // Dispose
  34276. /**
  34277. * Disposes the Submesh.
  34278. * Returns nothing.
  34279. */
  34280. SubMesh.prototype.dispose = function () {
  34281. if (this._linesIndexBuffer) {
  34282. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34283. this._linesIndexBuffer = null;
  34284. }
  34285. // Remove from mesh
  34286. var index = this._mesh.subMeshes.indexOf(this);
  34287. this._mesh.subMeshes.splice(index, 1);
  34288. };
  34289. // Statics
  34290. /**
  34291. * Creates a new Submesh from the passed parameters :
  34292. * - materialIndex (integer) : the index of the main mesh material.
  34293. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34294. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34295. * - mesh (Mesh) : the main mesh to create the submesh from.
  34296. * - renderingMesh (optional Mesh) : rendering mesh.
  34297. */
  34298. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34299. var minVertexIndex = Number.MAX_VALUE;
  34300. var maxVertexIndex = -Number.MAX_VALUE;
  34301. renderingMesh = (renderingMesh || mesh);
  34302. var indices = renderingMesh.getIndices();
  34303. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34304. var vertexIndex = indices[index];
  34305. if (vertexIndex < minVertexIndex)
  34306. minVertexIndex = vertexIndex;
  34307. if (vertexIndex > maxVertexIndex)
  34308. maxVertexIndex = vertexIndex;
  34309. }
  34310. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34311. };
  34312. return SubMesh;
  34313. }(BaseSubMesh));
  34314. BABYLON.SubMesh = SubMesh;
  34315. })(BABYLON || (BABYLON = {}));
  34316. //# sourceMappingURL=babylon.subMesh.js.map
  34317. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34318. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34319. s = arguments[i];
  34320. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34321. t[p] = s[p];
  34322. }
  34323. return t;
  34324. };
  34325. var BABYLON;
  34326. (function (BABYLON) {
  34327. /**
  34328. * Manages the defines for the Material
  34329. */
  34330. var MaterialDefines = /** @class */ (function () {
  34331. function MaterialDefines() {
  34332. this._isDirty = true;
  34333. /** @hidden */
  34334. this._areLightsDirty = true;
  34335. /** @hidden */
  34336. this._areAttributesDirty = true;
  34337. /** @hidden */
  34338. this._areTexturesDirty = true;
  34339. /** @hidden */
  34340. this._areFresnelDirty = true;
  34341. /** @hidden */
  34342. this._areMiscDirty = true;
  34343. /** @hidden */
  34344. this._areImageProcessingDirty = true;
  34345. /** @hidden */
  34346. this._normals = false;
  34347. /** @hidden */
  34348. this._uvs = false;
  34349. /** @hidden */
  34350. this._needNormals = false;
  34351. /** @hidden */
  34352. this._needUVs = false;
  34353. }
  34354. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34355. /**
  34356. * Specifies if the material needs to be re-calculated
  34357. */
  34358. get: function () {
  34359. return this._isDirty;
  34360. },
  34361. enumerable: true,
  34362. configurable: true
  34363. });
  34364. /**
  34365. * Marks the material to indicate that it has been re-calculated
  34366. */
  34367. MaterialDefines.prototype.markAsProcessed = function () {
  34368. this._isDirty = false;
  34369. this._areAttributesDirty = false;
  34370. this._areTexturesDirty = false;
  34371. this._areFresnelDirty = false;
  34372. this._areLightsDirty = false;
  34373. this._areMiscDirty = false;
  34374. this._areImageProcessingDirty = false;
  34375. };
  34376. /**
  34377. * Marks the material to indicate that it needs to be re-calculated
  34378. */
  34379. MaterialDefines.prototype.markAsUnprocessed = function () {
  34380. this._isDirty = true;
  34381. };
  34382. /**
  34383. * Marks the material to indicate all of its defines need to be re-calculated
  34384. */
  34385. MaterialDefines.prototype.markAllAsDirty = function () {
  34386. this._areTexturesDirty = true;
  34387. this._areAttributesDirty = true;
  34388. this._areLightsDirty = true;
  34389. this._areFresnelDirty = true;
  34390. this._areMiscDirty = true;
  34391. this._areImageProcessingDirty = true;
  34392. this._isDirty = true;
  34393. };
  34394. /**
  34395. * Marks the material to indicate that image processing needs to be re-calculated
  34396. */
  34397. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34398. this._areImageProcessingDirty = true;
  34399. this._isDirty = true;
  34400. };
  34401. /**
  34402. * Marks the material to indicate the lights need to be re-calculated
  34403. */
  34404. MaterialDefines.prototype.markAsLightDirty = function () {
  34405. this._areLightsDirty = true;
  34406. this._isDirty = true;
  34407. };
  34408. /**
  34409. * Marks the attribute state as changed
  34410. */
  34411. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34412. this._areAttributesDirty = true;
  34413. this._isDirty = true;
  34414. };
  34415. /**
  34416. * Marks the texture state as changed
  34417. */
  34418. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34419. this._areTexturesDirty = true;
  34420. this._isDirty = true;
  34421. };
  34422. /**
  34423. * Marks the fresnel state as changed
  34424. */
  34425. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34426. this._areFresnelDirty = true;
  34427. this._isDirty = true;
  34428. };
  34429. /**
  34430. * Marks the misc state as changed
  34431. */
  34432. MaterialDefines.prototype.markAsMiscDirty = function () {
  34433. this._areMiscDirty = true;
  34434. this._isDirty = true;
  34435. };
  34436. /**
  34437. * Rebuilds the material defines
  34438. */
  34439. MaterialDefines.prototype.rebuild = function () {
  34440. if (this._keys) {
  34441. delete this._keys;
  34442. }
  34443. this._keys = [];
  34444. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34445. var key = _a[_i];
  34446. if (key[0] === "_") {
  34447. continue;
  34448. }
  34449. this._keys.push(key);
  34450. }
  34451. };
  34452. /**
  34453. * Specifies if two material defines are equal
  34454. * @param other - A material define instance to compare to
  34455. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34456. */
  34457. MaterialDefines.prototype.isEqual = function (other) {
  34458. if (this._keys.length !== other._keys.length) {
  34459. return false;
  34460. }
  34461. for (var index = 0; index < this._keys.length; index++) {
  34462. var prop = this._keys[index];
  34463. if (this[prop] !== other[prop]) {
  34464. return false;
  34465. }
  34466. }
  34467. return true;
  34468. };
  34469. /**
  34470. * Clones this instance's defines to another instance
  34471. * @param other - material defines to clone values to
  34472. */
  34473. MaterialDefines.prototype.cloneTo = function (other) {
  34474. if (this._keys.length !== other._keys.length) {
  34475. other._keys = this._keys.slice(0);
  34476. }
  34477. for (var index = 0; index < this._keys.length; index++) {
  34478. var prop = this._keys[index];
  34479. other[prop] = this[prop];
  34480. }
  34481. };
  34482. /**
  34483. * Resets the material define values
  34484. */
  34485. MaterialDefines.prototype.reset = function () {
  34486. for (var index = 0; index < this._keys.length; index++) {
  34487. var prop = this._keys[index];
  34488. var type = typeof this[prop];
  34489. switch (type) {
  34490. case "number":
  34491. this[prop] = 0;
  34492. break;
  34493. case "string":
  34494. this[prop] = "";
  34495. break;
  34496. default:
  34497. this[prop] = false;
  34498. break;
  34499. }
  34500. }
  34501. };
  34502. /**
  34503. * Converts the material define values to a string
  34504. * @returns - String of material define information
  34505. */
  34506. MaterialDefines.prototype.toString = function () {
  34507. var result = "";
  34508. for (var index = 0; index < this._keys.length; index++) {
  34509. var prop = this._keys[index];
  34510. var value = this[prop];
  34511. var type = typeof value;
  34512. switch (type) {
  34513. case "number":
  34514. case "string":
  34515. result += "#define " + prop + " " + value + "\n";
  34516. break;
  34517. default:
  34518. if (value) {
  34519. result += "#define " + prop + "\n";
  34520. }
  34521. break;
  34522. }
  34523. }
  34524. return result;
  34525. };
  34526. return MaterialDefines;
  34527. }());
  34528. BABYLON.MaterialDefines = MaterialDefines;
  34529. /**
  34530. * Base class for the main features of a material in Babylon.js
  34531. */
  34532. var Material = /** @class */ (function () {
  34533. /**
  34534. * Creates a material instance
  34535. * @param name defines the name of the material
  34536. * @param scene defines the scene to reference
  34537. * @param doNotAdd specifies if the material should be added to the scene
  34538. */
  34539. function Material(name, scene, doNotAdd) {
  34540. /**
  34541. * Specifies if the ready state should be checked on each call
  34542. */
  34543. this.checkReadyOnEveryCall = false;
  34544. /**
  34545. * Specifies if the ready state should be checked once
  34546. */
  34547. this.checkReadyOnlyOnce = false;
  34548. /**
  34549. * The state of the material
  34550. */
  34551. this.state = "";
  34552. /**
  34553. * The alpha value of the material
  34554. */
  34555. this._alpha = 1.0;
  34556. /**
  34557. * Specifies if back face culling is enabled
  34558. */
  34559. this._backFaceCulling = true;
  34560. /**
  34561. * Specifies if the material should be serialized
  34562. */
  34563. this.doNotSerialize = false;
  34564. /**
  34565. * Specifies if the effect should be stored on sub meshes
  34566. */
  34567. this.storeEffectOnSubMeshes = false;
  34568. /**
  34569. * An event triggered when the material is disposed
  34570. */
  34571. this.onDisposeObservable = new BABYLON.Observable();
  34572. /**
  34573. * An event triggered when the material is bound
  34574. */
  34575. this.onBindObservable = new BABYLON.Observable();
  34576. /**
  34577. * An event triggered when the material is unbound
  34578. */
  34579. this.onUnBindObservable = new BABYLON.Observable();
  34580. /**
  34581. * Stores the value of the alpha mode
  34582. */
  34583. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34584. /**
  34585. * Stores the state of the need depth pre-pass value
  34586. */
  34587. this._needDepthPrePass = false;
  34588. /**
  34589. * Specifies if depth writing should be disabled
  34590. */
  34591. this.disableDepthWrite = false;
  34592. /**
  34593. * Specifies if depth writing should be forced
  34594. */
  34595. this.forceDepthWrite = false;
  34596. /**
  34597. * Specifies if there should be a separate pass for culling
  34598. */
  34599. this.separateCullingPass = false;
  34600. /**
  34601. * Stores the state specifing if fog should be enabled
  34602. */
  34603. this._fogEnabled = true;
  34604. /**
  34605. * Stores the size of points
  34606. */
  34607. this.pointSize = 1.0;
  34608. /**
  34609. * Stores the z offset value
  34610. */
  34611. this.zOffset = 0;
  34612. /**
  34613. * Specifies if the material was previously ready
  34614. */
  34615. this._wasPreviouslyReady = false;
  34616. /**
  34617. * Stores the fill mode state
  34618. */
  34619. this._fillMode = Material.TriangleFillMode;
  34620. this.name = name;
  34621. this.id = name || BABYLON.Tools.RandomId();
  34622. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34623. if (this._scene.useRightHandedSystem) {
  34624. this.sideOrientation = Material.ClockWiseSideOrientation;
  34625. }
  34626. else {
  34627. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34628. }
  34629. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34630. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34631. if (!doNotAdd) {
  34632. this._scene.materials.push(this);
  34633. }
  34634. }
  34635. Object.defineProperty(Material, "TriangleFillMode", {
  34636. /**
  34637. * Returns the triangle fill mode
  34638. */
  34639. get: function () {
  34640. return Material._TriangleFillMode;
  34641. },
  34642. enumerable: true,
  34643. configurable: true
  34644. });
  34645. Object.defineProperty(Material, "WireFrameFillMode", {
  34646. /**
  34647. * Returns the wireframe mode
  34648. */
  34649. get: function () {
  34650. return Material._WireFrameFillMode;
  34651. },
  34652. enumerable: true,
  34653. configurable: true
  34654. });
  34655. Object.defineProperty(Material, "PointFillMode", {
  34656. /**
  34657. * Returns the point fill mode
  34658. */
  34659. get: function () {
  34660. return Material._PointFillMode;
  34661. },
  34662. enumerable: true,
  34663. configurable: true
  34664. });
  34665. Object.defineProperty(Material, "PointListDrawMode", {
  34666. /**
  34667. * Returns the point list draw mode
  34668. */
  34669. get: function () {
  34670. return Material._PointListDrawMode;
  34671. },
  34672. enumerable: true,
  34673. configurable: true
  34674. });
  34675. Object.defineProperty(Material, "LineListDrawMode", {
  34676. /**
  34677. * Returns the line list draw mode
  34678. */
  34679. get: function () {
  34680. return Material._LineListDrawMode;
  34681. },
  34682. enumerable: true,
  34683. configurable: true
  34684. });
  34685. Object.defineProperty(Material, "LineLoopDrawMode", {
  34686. /**
  34687. * Returns the line loop draw mode
  34688. */
  34689. get: function () {
  34690. return Material._LineLoopDrawMode;
  34691. },
  34692. enumerable: true,
  34693. configurable: true
  34694. });
  34695. Object.defineProperty(Material, "LineStripDrawMode", {
  34696. /**
  34697. * Returns the line strip draw mode
  34698. */
  34699. get: function () {
  34700. return Material._LineStripDrawMode;
  34701. },
  34702. enumerable: true,
  34703. configurable: true
  34704. });
  34705. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34706. /**
  34707. * Returns the triangle strip draw mode
  34708. */
  34709. get: function () {
  34710. return Material._TriangleStripDrawMode;
  34711. },
  34712. enumerable: true,
  34713. configurable: true
  34714. });
  34715. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34716. /**
  34717. * Returns the triangle fan draw mode
  34718. */
  34719. get: function () {
  34720. return Material._TriangleFanDrawMode;
  34721. },
  34722. enumerable: true,
  34723. configurable: true
  34724. });
  34725. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34726. /**
  34727. * Returns the clock-wise side orientation
  34728. */
  34729. get: function () {
  34730. return Material._ClockWiseSideOrientation;
  34731. },
  34732. enumerable: true,
  34733. configurable: true
  34734. });
  34735. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34736. /**
  34737. * Returns the counter clock-wise side orientation
  34738. */
  34739. get: function () {
  34740. return Material._CounterClockWiseSideOrientation;
  34741. },
  34742. enumerable: true,
  34743. configurable: true
  34744. });
  34745. Object.defineProperty(Material, "TextureDirtyFlag", {
  34746. /**
  34747. * Returns the dirty texture flag value
  34748. */
  34749. get: function () {
  34750. return Material._TextureDirtyFlag;
  34751. },
  34752. enumerable: true,
  34753. configurable: true
  34754. });
  34755. Object.defineProperty(Material, "LightDirtyFlag", {
  34756. /**
  34757. * Returns the dirty light flag value
  34758. */
  34759. get: function () {
  34760. return Material._LightDirtyFlag;
  34761. },
  34762. enumerable: true,
  34763. configurable: true
  34764. });
  34765. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34766. /**
  34767. * Returns the dirty fresnel flag value
  34768. */
  34769. get: function () {
  34770. return Material._FresnelDirtyFlag;
  34771. },
  34772. enumerable: true,
  34773. configurable: true
  34774. });
  34775. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34776. /**
  34777. * Returns the dirty attributes flag value
  34778. */
  34779. get: function () {
  34780. return Material._AttributesDirtyFlag;
  34781. },
  34782. enumerable: true,
  34783. configurable: true
  34784. });
  34785. Object.defineProperty(Material, "MiscDirtyFlag", {
  34786. /**
  34787. * Returns the dirty misc flag value
  34788. */
  34789. get: function () {
  34790. return Material._MiscDirtyFlag;
  34791. },
  34792. enumerable: true,
  34793. configurable: true
  34794. });
  34795. Object.defineProperty(Material.prototype, "alpha", {
  34796. /**
  34797. * Gets the alpha value of the material
  34798. */
  34799. get: function () {
  34800. return this._alpha;
  34801. },
  34802. /**
  34803. * Sets the alpha value of the material
  34804. */
  34805. set: function (value) {
  34806. if (this._alpha === value) {
  34807. return;
  34808. }
  34809. this._alpha = value;
  34810. this.markAsDirty(Material.MiscDirtyFlag);
  34811. },
  34812. enumerable: true,
  34813. configurable: true
  34814. });
  34815. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34816. /**
  34817. * Gets the back-face culling state
  34818. */
  34819. get: function () {
  34820. return this._backFaceCulling;
  34821. },
  34822. /**
  34823. * Sets the back-face culling state
  34824. */
  34825. set: function (value) {
  34826. if (this._backFaceCulling === value) {
  34827. return;
  34828. }
  34829. this._backFaceCulling = value;
  34830. this.markAsDirty(Material.TextureDirtyFlag);
  34831. },
  34832. enumerable: true,
  34833. configurable: true
  34834. });
  34835. Object.defineProperty(Material.prototype, "onDispose", {
  34836. /**
  34837. * Called during a dispose event
  34838. */
  34839. set: function (callback) {
  34840. if (this._onDisposeObserver) {
  34841. this.onDisposeObservable.remove(this._onDisposeObserver);
  34842. }
  34843. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34844. },
  34845. enumerable: true,
  34846. configurable: true
  34847. });
  34848. Object.defineProperty(Material.prototype, "onBind", {
  34849. /**
  34850. * Called during a bind event
  34851. */
  34852. set: function (callback) {
  34853. if (this._onBindObserver) {
  34854. this.onBindObservable.remove(this._onBindObserver);
  34855. }
  34856. this._onBindObserver = this.onBindObservable.add(callback);
  34857. },
  34858. enumerable: true,
  34859. configurable: true
  34860. });
  34861. Object.defineProperty(Material.prototype, "alphaMode", {
  34862. /**
  34863. * Gets the value of the alpha mode
  34864. */
  34865. get: function () {
  34866. return this._alphaMode;
  34867. },
  34868. /**
  34869. * Sets the value of the alpha mode.
  34870. *
  34871. * | Value | Type | Description |
  34872. * | --- | --- | --- |
  34873. * | 0 | ALPHA_DISABLE | |
  34874. * | 1 | ALPHA_ADD | |
  34875. * | 2 | ALPHA_COMBINE | |
  34876. * | 3 | ALPHA_SUBTRACT | |
  34877. * | 4 | ALPHA_MULTIPLY | |
  34878. * | 5 | ALPHA_MAXIMIZED | |
  34879. * | 6 | ALPHA_ONEONE | |
  34880. * | 7 | ALPHA_PREMULTIPLIED | |
  34881. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34882. * | 9 | ALPHA_INTERPOLATE | |
  34883. * | 10 | ALPHA_SCREENMODE | |
  34884. *
  34885. */
  34886. set: function (value) {
  34887. if (this._alphaMode === value) {
  34888. return;
  34889. }
  34890. this._alphaMode = value;
  34891. this.markAsDirty(Material.TextureDirtyFlag);
  34892. },
  34893. enumerable: true,
  34894. configurable: true
  34895. });
  34896. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34897. /**
  34898. * Gets the depth pre-pass value
  34899. */
  34900. get: function () {
  34901. return this._needDepthPrePass;
  34902. },
  34903. /**
  34904. * Sets the need depth pre-pass value
  34905. */
  34906. set: function (value) {
  34907. if (this._needDepthPrePass === value) {
  34908. return;
  34909. }
  34910. this._needDepthPrePass = value;
  34911. if (this._needDepthPrePass) {
  34912. this.checkReadyOnEveryCall = true;
  34913. }
  34914. },
  34915. enumerable: true,
  34916. configurable: true
  34917. });
  34918. Object.defineProperty(Material.prototype, "fogEnabled", {
  34919. /**
  34920. * Gets the value of the fog enabled state
  34921. */
  34922. get: function () {
  34923. return this._fogEnabled;
  34924. },
  34925. /**
  34926. * Sets the state for enabling fog
  34927. */
  34928. set: function (value) {
  34929. if (this._fogEnabled === value) {
  34930. return;
  34931. }
  34932. this._fogEnabled = value;
  34933. this.markAsDirty(Material.MiscDirtyFlag);
  34934. },
  34935. enumerable: true,
  34936. configurable: true
  34937. });
  34938. Object.defineProperty(Material.prototype, "wireframe", {
  34939. /**
  34940. * Gets a value specifying if wireframe mode is enabled
  34941. */
  34942. get: function () {
  34943. switch (this._fillMode) {
  34944. case Material.WireFrameFillMode:
  34945. case Material.LineListDrawMode:
  34946. case Material.LineLoopDrawMode:
  34947. case Material.LineStripDrawMode:
  34948. return true;
  34949. }
  34950. return this._scene.forceWireframe;
  34951. },
  34952. /**
  34953. * Sets the state of wireframe mode
  34954. */
  34955. set: function (value) {
  34956. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34957. },
  34958. enumerable: true,
  34959. configurable: true
  34960. });
  34961. Object.defineProperty(Material.prototype, "pointsCloud", {
  34962. /**
  34963. * Gets the value specifying if point clouds are enabled
  34964. */
  34965. get: function () {
  34966. switch (this._fillMode) {
  34967. case Material.PointFillMode:
  34968. case Material.PointListDrawMode:
  34969. return true;
  34970. }
  34971. return this._scene.forcePointsCloud;
  34972. },
  34973. /**
  34974. * Sets the state of point cloud mode
  34975. */
  34976. set: function (value) {
  34977. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34978. },
  34979. enumerable: true,
  34980. configurable: true
  34981. });
  34982. Object.defineProperty(Material.prototype, "fillMode", {
  34983. /**
  34984. * Gets the material fill mode
  34985. */
  34986. get: function () {
  34987. return this._fillMode;
  34988. },
  34989. /**
  34990. * Sets the material fill mode
  34991. */
  34992. set: function (value) {
  34993. if (this._fillMode === value) {
  34994. return;
  34995. }
  34996. this._fillMode = value;
  34997. this.markAsDirty(Material.MiscDirtyFlag);
  34998. },
  34999. enumerable: true,
  35000. configurable: true
  35001. });
  35002. /**
  35003. * Returns a string representation of the current material
  35004. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35005. * @returns a string with material information
  35006. */
  35007. Material.prototype.toString = function (fullDetails) {
  35008. var ret = "Name: " + this.name;
  35009. if (fullDetails) {
  35010. }
  35011. return ret;
  35012. };
  35013. /**
  35014. * Gets the class name of the material
  35015. * @returns a string with the class name of the material
  35016. */
  35017. Material.prototype.getClassName = function () {
  35018. return "Material";
  35019. };
  35020. Object.defineProperty(Material.prototype, "isFrozen", {
  35021. /**
  35022. * Specifies if updates for the material been locked
  35023. */
  35024. get: function () {
  35025. return this.checkReadyOnlyOnce;
  35026. },
  35027. enumerable: true,
  35028. configurable: true
  35029. });
  35030. /**
  35031. * Locks updates for the material
  35032. */
  35033. Material.prototype.freeze = function () {
  35034. this.checkReadyOnlyOnce = true;
  35035. };
  35036. /**
  35037. * Unlocks updates for the material
  35038. */
  35039. Material.prototype.unfreeze = function () {
  35040. this.checkReadyOnlyOnce = false;
  35041. };
  35042. /**
  35043. * Specifies if the material is ready to be used
  35044. * @param mesh defines the mesh to check
  35045. * @param useInstances specifies if instances should be used
  35046. * @returns a boolean indicating if the material is ready to be used
  35047. */
  35048. Material.prototype.isReady = function (mesh, useInstances) {
  35049. return true;
  35050. };
  35051. /**
  35052. * Specifies that the submesh is ready to be used
  35053. * @param mesh defines the mesh to check
  35054. * @param subMesh defines which submesh to check
  35055. * @param useInstances specifies that instances should be used
  35056. * @returns a boolean indicating that the submesh is ready or not
  35057. */
  35058. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35059. return false;
  35060. };
  35061. /**
  35062. * Returns the material effect
  35063. * @returns the effect associated with the material
  35064. */
  35065. Material.prototype.getEffect = function () {
  35066. return this._effect;
  35067. };
  35068. /**
  35069. * Returns the current scene
  35070. * @returns a Scene
  35071. */
  35072. Material.prototype.getScene = function () {
  35073. return this._scene;
  35074. };
  35075. /**
  35076. * Specifies if the material will require alpha blending
  35077. * @returns a boolean specifying if alpha blending is needed
  35078. */
  35079. Material.prototype.needAlphaBlending = function () {
  35080. return (this.alpha < 1.0);
  35081. };
  35082. /**
  35083. * Specifies if the mesh will require alpha blending
  35084. * @param mesh defines the mesh to check
  35085. * @returns a boolean specifying if alpha blending is needed for the mesh
  35086. */
  35087. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35088. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35089. };
  35090. /**
  35091. * Specifies if this material should be rendered in alpha test mode
  35092. * @returns a boolean specifying if an alpha test is needed.
  35093. */
  35094. Material.prototype.needAlphaTesting = function () {
  35095. return false;
  35096. };
  35097. /**
  35098. * Gets the texture used for the alpha test
  35099. * @returns the texture to use for alpha testing
  35100. */
  35101. Material.prototype.getAlphaTestTexture = function () {
  35102. return null;
  35103. };
  35104. /**
  35105. * Marks the material to indicate that it needs to be re-calculated
  35106. */
  35107. Material.prototype.markDirty = function () {
  35108. this._wasPreviouslyReady = false;
  35109. };
  35110. /** @hidden */
  35111. Material.prototype._preBind = function (effect, overrideOrientation) {
  35112. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35113. var engine = this._scene.getEngine();
  35114. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35115. var reverse = orientation === Material.ClockWiseSideOrientation;
  35116. engine.enableEffect(effect ? effect : this._effect);
  35117. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35118. return reverse;
  35119. };
  35120. /**
  35121. * Binds the material to the mesh
  35122. * @param world defines the world transformation matrix
  35123. * @param mesh defines the mesh to bind the material to
  35124. */
  35125. Material.prototype.bind = function (world, mesh) {
  35126. };
  35127. /**
  35128. * Binds the submesh to the material
  35129. * @param world defines the world transformation matrix
  35130. * @param mesh defines the mesh containing the submesh
  35131. * @param subMesh defines the submesh to bind the material to
  35132. */
  35133. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35134. };
  35135. /**
  35136. * Binds the world matrix to the material
  35137. * @param world defines the world transformation matrix
  35138. */
  35139. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35140. };
  35141. /**
  35142. * Binds the scene's uniform buffer to the effect.
  35143. * @param effect defines the effect to bind to the scene uniform buffer
  35144. * @param sceneUbo defines the uniform buffer storing scene data
  35145. */
  35146. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35147. sceneUbo.bindToEffect(effect, "Scene");
  35148. };
  35149. /**
  35150. * Binds the view matrix to the effect
  35151. * @param effect defines the effect to bind the view matrix to
  35152. */
  35153. Material.prototype.bindView = function (effect) {
  35154. if (!this._useUBO) {
  35155. effect.setMatrix("view", this.getScene().getViewMatrix());
  35156. }
  35157. else {
  35158. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35159. }
  35160. };
  35161. /**
  35162. * Binds the view projection matrix to the effect
  35163. * @param effect defines the effect to bind the view projection matrix to
  35164. */
  35165. Material.prototype.bindViewProjection = function (effect) {
  35166. if (!this._useUBO) {
  35167. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35168. }
  35169. else {
  35170. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35171. }
  35172. };
  35173. /**
  35174. * Specifies if material alpha testing should be turned on for the mesh
  35175. * @param mesh defines the mesh to check
  35176. */
  35177. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35178. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35179. };
  35180. /**
  35181. * Processes to execute after binding the material to a mesh
  35182. * @param mesh defines the rendered mesh
  35183. */
  35184. Material.prototype._afterBind = function (mesh) {
  35185. this._scene._cachedMaterial = this;
  35186. if (mesh) {
  35187. this._scene._cachedVisibility = mesh.visibility;
  35188. }
  35189. else {
  35190. this._scene._cachedVisibility = 1;
  35191. }
  35192. if (mesh) {
  35193. this.onBindObservable.notifyObservers(mesh);
  35194. }
  35195. if (this.disableDepthWrite) {
  35196. var engine = this._scene.getEngine();
  35197. this._cachedDepthWriteState = engine.getDepthWrite();
  35198. engine.setDepthWrite(false);
  35199. }
  35200. };
  35201. /**
  35202. * Unbinds the material from the mesh
  35203. */
  35204. Material.prototype.unbind = function () {
  35205. this.onUnBindObservable.notifyObservers(this);
  35206. if (this.disableDepthWrite) {
  35207. var engine = this._scene.getEngine();
  35208. engine.setDepthWrite(this._cachedDepthWriteState);
  35209. }
  35210. };
  35211. /**
  35212. * Gets the active textures from the material
  35213. * @returns an array of textures
  35214. */
  35215. Material.prototype.getActiveTextures = function () {
  35216. return [];
  35217. };
  35218. /**
  35219. * Specifies if the material uses a texture
  35220. * @param texture defines the texture to check against the material
  35221. * @returns a boolean specifying if the material uses the texture
  35222. */
  35223. Material.prototype.hasTexture = function (texture) {
  35224. return false;
  35225. };
  35226. /**
  35227. * Makes a duplicate of the material, and gives it a new name
  35228. * @param name defines the new name for the duplicated material
  35229. * @returns the cloned material
  35230. */
  35231. Material.prototype.clone = function (name) {
  35232. return null;
  35233. };
  35234. /**
  35235. * Gets the meshes bound to the material
  35236. * @returns an array of meshes bound to the material
  35237. */
  35238. Material.prototype.getBindedMeshes = function () {
  35239. var result = new Array();
  35240. for (var index = 0; index < this._scene.meshes.length; index++) {
  35241. var mesh = this._scene.meshes[index];
  35242. if (mesh.material === this) {
  35243. result.push(mesh);
  35244. }
  35245. }
  35246. return result;
  35247. };
  35248. /**
  35249. * Force shader compilation
  35250. * @param mesh defines the mesh associated with this material
  35251. * @param onCompiled defines a function to execute once the material is compiled
  35252. * @param options defines the options to configure the compilation
  35253. */
  35254. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35255. var _this = this;
  35256. var localOptions = __assign({ clipPlane: false }, options);
  35257. var subMesh = new BABYLON.BaseSubMesh();
  35258. var scene = this.getScene();
  35259. var checkReady = function () {
  35260. if (!_this._scene || !_this._scene.getEngine()) {
  35261. return;
  35262. }
  35263. if (subMesh._materialDefines) {
  35264. subMesh._materialDefines._renderId = -1;
  35265. }
  35266. var clipPlaneState = scene.clipPlane;
  35267. if (localOptions.clipPlane) {
  35268. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35269. }
  35270. if (_this.storeEffectOnSubMeshes) {
  35271. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35272. if (onCompiled) {
  35273. onCompiled(_this);
  35274. }
  35275. }
  35276. else {
  35277. setTimeout(checkReady, 16);
  35278. }
  35279. }
  35280. else {
  35281. if (_this.isReady(mesh)) {
  35282. if (onCompiled) {
  35283. onCompiled(_this);
  35284. }
  35285. }
  35286. else {
  35287. setTimeout(checkReady, 16);
  35288. }
  35289. }
  35290. if (localOptions.clipPlane) {
  35291. scene.clipPlane = clipPlaneState;
  35292. }
  35293. };
  35294. checkReady();
  35295. };
  35296. /**
  35297. * Force shader compilation
  35298. * @param mesh defines the mesh that will use this material
  35299. * @param options defines additional options for compiling the shaders
  35300. * @returns a promise that resolves when the compilation completes
  35301. */
  35302. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35303. var _this = this;
  35304. return new Promise(function (resolve) {
  35305. _this.forceCompilation(mesh, function () {
  35306. resolve();
  35307. }, options);
  35308. });
  35309. };
  35310. /**
  35311. * Marks a define in the material to indicate that it needs to be re-computed
  35312. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35313. */
  35314. Material.prototype.markAsDirty = function (flag) {
  35315. if (flag & Material.TextureDirtyFlag) {
  35316. this._markAllSubMeshesAsTexturesDirty();
  35317. }
  35318. if (flag & Material.LightDirtyFlag) {
  35319. this._markAllSubMeshesAsLightsDirty();
  35320. }
  35321. if (flag & Material.FresnelDirtyFlag) {
  35322. this._markAllSubMeshesAsFresnelDirty();
  35323. }
  35324. if (flag & Material.AttributesDirtyFlag) {
  35325. this._markAllSubMeshesAsAttributesDirty();
  35326. }
  35327. if (flag & Material.MiscDirtyFlag) {
  35328. this._markAllSubMeshesAsMiscDirty();
  35329. }
  35330. this.getScene().resetCachedMaterial();
  35331. };
  35332. /**
  35333. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35334. * @param func defines a function which checks material defines against the submeshes
  35335. */
  35336. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35337. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35338. var mesh = _a[_i];
  35339. if (!mesh.subMeshes) {
  35340. continue;
  35341. }
  35342. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35343. var subMesh = _c[_b];
  35344. if (subMesh.getMaterial() !== this) {
  35345. continue;
  35346. }
  35347. if (!subMesh._materialDefines) {
  35348. continue;
  35349. }
  35350. func(subMesh._materialDefines);
  35351. }
  35352. }
  35353. };
  35354. /**
  35355. * Indicates that image processing needs to be re-calculated for all submeshes
  35356. */
  35357. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35358. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35359. };
  35360. /**
  35361. * Indicates that textures need to be re-calculated for all submeshes
  35362. */
  35363. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35364. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35365. };
  35366. /**
  35367. * Indicates that fresnel needs to be re-calculated for all submeshes
  35368. */
  35369. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35370. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35371. };
  35372. /**
  35373. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35374. */
  35375. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35376. this._markAllSubMeshesAsDirty(function (defines) {
  35377. defines.markAsFresnelDirty();
  35378. defines.markAsMiscDirty();
  35379. });
  35380. };
  35381. /**
  35382. * Indicates that lights need to be re-calculated for all submeshes
  35383. */
  35384. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35385. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35386. };
  35387. /**
  35388. * Indicates that attributes need to be re-calculated for all submeshes
  35389. */
  35390. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35391. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35392. };
  35393. /**
  35394. * Indicates that misc needs to be re-calculated for all submeshes
  35395. */
  35396. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35397. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35398. };
  35399. /**
  35400. * Indicates that textures and misc need to be re-calculated for all submeshes
  35401. */
  35402. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35403. this._markAllSubMeshesAsDirty(function (defines) {
  35404. defines.markAsTexturesDirty();
  35405. defines.markAsMiscDirty();
  35406. });
  35407. };
  35408. /**
  35409. * Disposes the material
  35410. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35411. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35412. */
  35413. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35414. // Animations
  35415. this.getScene().stopAnimation(this);
  35416. this.getScene().freeProcessedMaterials();
  35417. // Remove from scene
  35418. var index = this._scene.materials.indexOf(this);
  35419. if (index >= 0) {
  35420. this._scene.materials.splice(index, 1);
  35421. }
  35422. // Remove from meshes
  35423. for (index = 0; index < this._scene.meshes.length; index++) {
  35424. var mesh = this._scene.meshes[index];
  35425. if (mesh.material === this) {
  35426. mesh.material = null;
  35427. if (mesh.geometry) {
  35428. var geometry = (mesh.geometry);
  35429. if (this.storeEffectOnSubMeshes) {
  35430. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35431. var subMesh = _a[_i];
  35432. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35433. if (forceDisposeEffect && subMesh._materialEffect) {
  35434. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35435. }
  35436. }
  35437. }
  35438. else {
  35439. geometry._releaseVertexArrayObject(this._effect);
  35440. }
  35441. }
  35442. }
  35443. }
  35444. this._uniformBuffer.dispose();
  35445. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35446. if (forceDisposeEffect && this._effect) {
  35447. if (!this.storeEffectOnSubMeshes) {
  35448. this._scene.getEngine()._releaseEffect(this._effect);
  35449. }
  35450. this._effect = null;
  35451. }
  35452. // Callback
  35453. this.onDisposeObservable.notifyObservers(this);
  35454. this.onDisposeObservable.clear();
  35455. this.onBindObservable.clear();
  35456. this.onUnBindObservable.clear();
  35457. };
  35458. /**
  35459. * Serializes this material
  35460. * @returns the serialized material object
  35461. */
  35462. Material.prototype.serialize = function () {
  35463. return BABYLON.SerializationHelper.Serialize(this);
  35464. };
  35465. /**
  35466. * Creates a MultiMaterial from parsed MultiMaterial data.
  35467. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35468. * @param scene defines the hosting scene
  35469. * @returns a new MultiMaterial
  35470. */
  35471. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35472. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35473. multiMaterial.id = parsedMultiMaterial.id;
  35474. if (BABYLON.Tags) {
  35475. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35476. }
  35477. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35478. var subMatId = parsedMultiMaterial.materials[matIndex];
  35479. if (subMatId) {
  35480. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35481. }
  35482. else {
  35483. multiMaterial.subMaterials.push(null);
  35484. }
  35485. }
  35486. return multiMaterial;
  35487. };
  35488. /**
  35489. * Creates a material from parsed material data
  35490. * @param parsedMaterial defines parsed material data
  35491. * @param scene defines the hosting scene
  35492. * @param rootUrl defines the root URL to use to load textures
  35493. * @returns a new material
  35494. */
  35495. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35496. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35497. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35498. }
  35499. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35500. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35501. if (!BABYLON.LegacyPBRMaterial) {
  35502. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35503. return;
  35504. }
  35505. }
  35506. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35507. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35508. };
  35509. // Triangle views
  35510. Material._TriangleFillMode = 0;
  35511. Material._WireFrameFillMode = 1;
  35512. Material._PointFillMode = 2;
  35513. // Draw modes
  35514. Material._PointListDrawMode = 3;
  35515. Material._LineListDrawMode = 4;
  35516. Material._LineLoopDrawMode = 5;
  35517. Material._LineStripDrawMode = 6;
  35518. Material._TriangleStripDrawMode = 7;
  35519. Material._TriangleFanDrawMode = 8;
  35520. /**
  35521. * Stores the clock-wise side orientation
  35522. */
  35523. Material._ClockWiseSideOrientation = 0;
  35524. /**
  35525. * Stores the counter clock-wise side orientation
  35526. */
  35527. Material._CounterClockWiseSideOrientation = 1;
  35528. /**
  35529. * The dirty texture flag value
  35530. */
  35531. Material._TextureDirtyFlag = 1;
  35532. /**
  35533. * The dirty light flag value
  35534. */
  35535. Material._LightDirtyFlag = 2;
  35536. /**
  35537. * The dirty fresnel flag value
  35538. */
  35539. Material._FresnelDirtyFlag = 4;
  35540. /**
  35541. * The dirty attribute flag value
  35542. */
  35543. Material._AttributesDirtyFlag = 8;
  35544. /**
  35545. * The dirty misc flag value
  35546. */
  35547. Material._MiscDirtyFlag = 16;
  35548. __decorate([
  35549. BABYLON.serialize()
  35550. ], Material.prototype, "id", void 0);
  35551. __decorate([
  35552. BABYLON.serialize()
  35553. ], Material.prototype, "name", void 0);
  35554. __decorate([
  35555. BABYLON.serialize()
  35556. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35557. __decorate([
  35558. BABYLON.serialize()
  35559. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35560. __decorate([
  35561. BABYLON.serialize()
  35562. ], Material.prototype, "state", void 0);
  35563. __decorate([
  35564. BABYLON.serialize("alpha")
  35565. ], Material.prototype, "_alpha", void 0);
  35566. __decorate([
  35567. BABYLON.serialize("backFaceCulling")
  35568. ], Material.prototype, "_backFaceCulling", void 0);
  35569. __decorate([
  35570. BABYLON.serialize()
  35571. ], Material.prototype, "sideOrientation", void 0);
  35572. __decorate([
  35573. BABYLON.serialize("alphaMode")
  35574. ], Material.prototype, "_alphaMode", void 0);
  35575. __decorate([
  35576. BABYLON.serialize()
  35577. ], Material.prototype, "_needDepthPrePass", void 0);
  35578. __decorate([
  35579. BABYLON.serialize()
  35580. ], Material.prototype, "disableDepthWrite", void 0);
  35581. __decorate([
  35582. BABYLON.serialize()
  35583. ], Material.prototype, "forceDepthWrite", void 0);
  35584. __decorate([
  35585. BABYLON.serialize()
  35586. ], Material.prototype, "separateCullingPass", void 0);
  35587. __decorate([
  35588. BABYLON.serialize("fogEnabled")
  35589. ], Material.prototype, "_fogEnabled", void 0);
  35590. __decorate([
  35591. BABYLON.serialize()
  35592. ], Material.prototype, "pointSize", void 0);
  35593. __decorate([
  35594. BABYLON.serialize()
  35595. ], Material.prototype, "zOffset", void 0);
  35596. __decorate([
  35597. BABYLON.serialize()
  35598. ], Material.prototype, "wireframe", null);
  35599. __decorate([
  35600. BABYLON.serialize()
  35601. ], Material.prototype, "pointsCloud", null);
  35602. __decorate([
  35603. BABYLON.serialize()
  35604. ], Material.prototype, "fillMode", null);
  35605. return Material;
  35606. }());
  35607. BABYLON.Material = Material;
  35608. })(BABYLON || (BABYLON = {}));
  35609. //# sourceMappingURL=babylon.material.js.map
  35610. var BABYLON;
  35611. (function (BABYLON) {
  35612. var UniformBuffer = /** @class */ (function () {
  35613. /**
  35614. * Uniform buffer objects.
  35615. *
  35616. * Handles blocks of uniform on the GPU.
  35617. *
  35618. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35619. *
  35620. * For more information, please refer to :
  35621. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35622. */
  35623. function UniformBuffer(engine, data, dynamic) {
  35624. this._engine = engine;
  35625. this._noUBO = !engine.supportsUniformBuffers;
  35626. this._dynamic = dynamic;
  35627. this._data = data || [];
  35628. this._uniformLocations = {};
  35629. this._uniformSizes = {};
  35630. this._uniformLocationPointer = 0;
  35631. this._needSync = false;
  35632. if (this._noUBO) {
  35633. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35634. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35635. this.updateFloat = this._updateFloatForEffect;
  35636. this.updateFloat2 = this._updateFloat2ForEffect;
  35637. this.updateFloat3 = this._updateFloat3ForEffect;
  35638. this.updateFloat4 = this._updateFloat4ForEffect;
  35639. this.updateMatrix = this._updateMatrixForEffect;
  35640. this.updateVector3 = this._updateVector3ForEffect;
  35641. this.updateVector4 = this._updateVector4ForEffect;
  35642. this.updateColor3 = this._updateColor3ForEffect;
  35643. this.updateColor4 = this._updateColor4ForEffect;
  35644. }
  35645. else {
  35646. this._engine._uniformBuffers.push(this);
  35647. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35648. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35649. this.updateFloat = this._updateFloatForUniform;
  35650. this.updateFloat2 = this._updateFloat2ForUniform;
  35651. this.updateFloat3 = this._updateFloat3ForUniform;
  35652. this.updateFloat4 = this._updateFloat4ForUniform;
  35653. this.updateMatrix = this._updateMatrixForUniform;
  35654. this.updateVector3 = this._updateVector3ForUniform;
  35655. this.updateVector4 = this._updateVector4ForUniform;
  35656. this.updateColor3 = this._updateColor3ForUniform;
  35657. this.updateColor4 = this._updateColor4ForUniform;
  35658. }
  35659. }
  35660. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35661. // Properties
  35662. /**
  35663. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35664. * or just falling back on setUniformXXX calls.
  35665. */
  35666. get: function () {
  35667. return !this._noUBO;
  35668. },
  35669. enumerable: true,
  35670. configurable: true
  35671. });
  35672. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35673. /**
  35674. * Indicates if the WebGL underlying uniform buffer is in sync
  35675. * with the javascript cache data.
  35676. */
  35677. get: function () {
  35678. return !this._needSync;
  35679. },
  35680. enumerable: true,
  35681. configurable: true
  35682. });
  35683. /**
  35684. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35685. * Also, a dynamic UniformBuffer will disable cache verification and always
  35686. * update the underlying WebGL uniform buffer to the GPU.
  35687. */
  35688. UniformBuffer.prototype.isDynamic = function () {
  35689. return this._dynamic !== undefined;
  35690. };
  35691. /**
  35692. * The data cache on JS side.
  35693. */
  35694. UniformBuffer.prototype.getData = function () {
  35695. return this._bufferData;
  35696. };
  35697. /**
  35698. * The underlying WebGL Uniform buffer.
  35699. */
  35700. UniformBuffer.prototype.getBuffer = function () {
  35701. return this._buffer;
  35702. };
  35703. /**
  35704. * std140 layout specifies how to align data within an UBO structure.
  35705. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35706. * for specs.
  35707. */
  35708. UniformBuffer.prototype._fillAlignment = function (size) {
  35709. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35710. // and 4x4 matrices
  35711. // TODO : change if other types are used
  35712. var alignment;
  35713. if (size <= 2) {
  35714. alignment = size;
  35715. }
  35716. else {
  35717. alignment = 4;
  35718. }
  35719. if ((this._uniformLocationPointer % alignment) !== 0) {
  35720. var oldPointer = this._uniformLocationPointer;
  35721. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35722. var diff = this._uniformLocationPointer - oldPointer;
  35723. for (var i = 0; i < diff; i++) {
  35724. this._data.push(0);
  35725. }
  35726. }
  35727. };
  35728. /**
  35729. * Adds an uniform in the buffer.
  35730. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35731. * for the layout to be correct !
  35732. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35733. * @param {number|number[]} size Data size, or data directly.
  35734. */
  35735. UniformBuffer.prototype.addUniform = function (name, size) {
  35736. if (this._noUBO) {
  35737. return;
  35738. }
  35739. if (this._uniformLocations[name] !== undefined) {
  35740. // Already existing uniform
  35741. return;
  35742. }
  35743. // This function must be called in the order of the shader layout !
  35744. // size can be the size of the uniform, or data directly
  35745. var data;
  35746. if (size instanceof Array) {
  35747. data = size;
  35748. size = data.length;
  35749. }
  35750. else {
  35751. size = size;
  35752. data = [];
  35753. // Fill with zeros
  35754. for (var i = 0; i < size; i++) {
  35755. data.push(0);
  35756. }
  35757. }
  35758. this._fillAlignment(size);
  35759. this._uniformSizes[name] = size;
  35760. this._uniformLocations[name] = this._uniformLocationPointer;
  35761. this._uniformLocationPointer += size;
  35762. for (var i = 0; i < size; i++) {
  35763. this._data.push(data[i]);
  35764. }
  35765. this._needSync = true;
  35766. };
  35767. /**
  35768. * Wrapper for addUniform.
  35769. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35770. * @param {Matrix} mat A 4x4 matrix.
  35771. */
  35772. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35773. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35774. };
  35775. /**
  35776. * Wrapper for addUniform.
  35777. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35778. * @param {number} x
  35779. * @param {number} y
  35780. */
  35781. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35782. var temp = [x, y];
  35783. this.addUniform(name, temp);
  35784. };
  35785. /**
  35786. * Wrapper for addUniform.
  35787. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35788. * @param {number} x
  35789. * @param {number} y
  35790. * @param {number} z
  35791. */
  35792. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35793. var temp = [x, y, z];
  35794. this.addUniform(name, temp);
  35795. };
  35796. /**
  35797. * Wrapper for addUniform.
  35798. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35799. * @param {Color3} color
  35800. */
  35801. UniformBuffer.prototype.addColor3 = function (name, color) {
  35802. var temp = new Array();
  35803. color.toArray(temp);
  35804. this.addUniform(name, temp);
  35805. };
  35806. /**
  35807. * Wrapper for addUniform.
  35808. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35809. * @param {Color3} color
  35810. * @param {number} alpha
  35811. */
  35812. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35813. var temp = new Array();
  35814. color.toArray(temp);
  35815. temp.push(alpha);
  35816. this.addUniform(name, temp);
  35817. };
  35818. /**
  35819. * Wrapper for addUniform.
  35820. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35821. * @param {Vector3} vector
  35822. */
  35823. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35824. var temp = new Array();
  35825. vector.toArray(temp);
  35826. this.addUniform(name, temp);
  35827. };
  35828. /**
  35829. * Wrapper for addUniform.
  35830. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35831. */
  35832. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35833. this.addUniform(name, 12);
  35834. };
  35835. /**
  35836. * Wrapper for addUniform.
  35837. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35838. */
  35839. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35840. this.addUniform(name, 8);
  35841. };
  35842. /**
  35843. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35844. */
  35845. UniformBuffer.prototype.create = function () {
  35846. if (this._noUBO) {
  35847. return;
  35848. }
  35849. if (this._buffer) {
  35850. return; // nothing to do
  35851. }
  35852. // See spec, alignment must be filled as a vec4
  35853. this._fillAlignment(4);
  35854. this._bufferData = new Float32Array(this._data);
  35855. this._rebuild();
  35856. this._needSync = true;
  35857. };
  35858. UniformBuffer.prototype._rebuild = function () {
  35859. if (this._noUBO) {
  35860. return;
  35861. }
  35862. if (this._dynamic) {
  35863. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35864. }
  35865. else {
  35866. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35867. }
  35868. };
  35869. /**
  35870. * Updates the WebGL Uniform Buffer on the GPU.
  35871. * If the `dynamic` flag is set to true, no cache comparison is done.
  35872. * Otherwise, the buffer will be updated only if the cache differs.
  35873. */
  35874. UniformBuffer.prototype.update = function () {
  35875. if (!this._buffer) {
  35876. this.create();
  35877. return;
  35878. }
  35879. if (!this._dynamic && !this._needSync) {
  35880. return;
  35881. }
  35882. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35883. this._needSync = false;
  35884. };
  35885. /**
  35886. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35887. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35888. * @param {number[]|Float32Array} data Flattened data
  35889. * @param {number} size Size of the data.
  35890. */
  35891. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35892. var location = this._uniformLocations[uniformName];
  35893. if (location === undefined) {
  35894. if (this._buffer) {
  35895. // Cannot add an uniform if the buffer is already created
  35896. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35897. return;
  35898. }
  35899. this.addUniform(uniformName, size);
  35900. location = this._uniformLocations[uniformName];
  35901. }
  35902. if (!this._buffer) {
  35903. this.create();
  35904. }
  35905. if (!this._dynamic) {
  35906. // Cache for static uniform buffers
  35907. var changed = false;
  35908. for (var i = 0; i < size; i++) {
  35909. if (this._bufferData[location + i] !== data[i]) {
  35910. changed = true;
  35911. this._bufferData[location + i] = data[i];
  35912. }
  35913. }
  35914. this._needSync = this._needSync || changed;
  35915. }
  35916. else {
  35917. // No cache for dynamic
  35918. for (var i = 0; i < size; i++) {
  35919. this._bufferData[location + i] = data[i];
  35920. }
  35921. }
  35922. };
  35923. // Update methods
  35924. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35925. // To match std140, matrix must be realigned
  35926. for (var i = 0; i < 3; i++) {
  35927. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35928. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35929. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35930. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35931. }
  35932. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35933. };
  35934. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35935. this._currentEffect.setMatrix3x3(name, matrix);
  35936. };
  35937. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35938. this._currentEffect.setMatrix2x2(name, matrix);
  35939. };
  35940. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35941. // To match std140, matrix must be realigned
  35942. for (var i = 0; i < 2; i++) {
  35943. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35944. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35945. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35946. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35947. }
  35948. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35949. };
  35950. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35951. this._currentEffect.setFloat(name, x);
  35952. };
  35953. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35954. UniformBuffer._tempBuffer[0] = x;
  35955. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35956. };
  35957. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35958. if (suffix === void 0) { suffix = ""; }
  35959. this._currentEffect.setFloat2(name + suffix, x, y);
  35960. };
  35961. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35962. if (suffix === void 0) { suffix = ""; }
  35963. UniformBuffer._tempBuffer[0] = x;
  35964. UniformBuffer._tempBuffer[1] = y;
  35965. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35966. };
  35967. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35968. if (suffix === void 0) { suffix = ""; }
  35969. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35970. };
  35971. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35972. if (suffix === void 0) { suffix = ""; }
  35973. UniformBuffer._tempBuffer[0] = x;
  35974. UniformBuffer._tempBuffer[1] = y;
  35975. UniformBuffer._tempBuffer[2] = z;
  35976. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35977. };
  35978. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35979. if (suffix === void 0) { suffix = ""; }
  35980. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35981. };
  35982. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35983. if (suffix === void 0) { suffix = ""; }
  35984. UniformBuffer._tempBuffer[0] = x;
  35985. UniformBuffer._tempBuffer[1] = y;
  35986. UniformBuffer._tempBuffer[2] = z;
  35987. UniformBuffer._tempBuffer[3] = w;
  35988. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35989. };
  35990. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35991. this._currentEffect.setMatrix(name, mat);
  35992. };
  35993. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35994. this.updateUniform(name, mat.toArray(), 16);
  35995. };
  35996. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35997. this._currentEffect.setVector3(name, vector);
  35998. };
  35999. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36000. vector.toArray(UniformBuffer._tempBuffer);
  36001. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36002. };
  36003. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36004. this._currentEffect.setVector4(name, vector);
  36005. };
  36006. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36007. vector.toArray(UniformBuffer._tempBuffer);
  36008. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36009. };
  36010. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36011. if (suffix === void 0) { suffix = ""; }
  36012. this._currentEffect.setColor3(name + suffix, color);
  36013. };
  36014. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36015. if (suffix === void 0) { suffix = ""; }
  36016. color.toArray(UniformBuffer._tempBuffer);
  36017. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36018. };
  36019. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36020. if (suffix === void 0) { suffix = ""; }
  36021. this._currentEffect.setColor4(name + suffix, color, alpha);
  36022. };
  36023. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36024. if (suffix === void 0) { suffix = ""; }
  36025. color.toArray(UniformBuffer._tempBuffer);
  36026. UniformBuffer._tempBuffer[3] = alpha;
  36027. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36028. };
  36029. /**
  36030. * Sets a sampler uniform on the effect.
  36031. * @param {string} name Name of the sampler.
  36032. * @param {Texture} texture
  36033. */
  36034. UniformBuffer.prototype.setTexture = function (name, texture) {
  36035. this._currentEffect.setTexture(name, texture);
  36036. };
  36037. /**
  36038. * Directly updates the value of the uniform in the cache AND on the GPU.
  36039. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36040. * @param {number[]|Float32Array} data Flattened data
  36041. */
  36042. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36043. this.updateUniform(uniformName, data, data.length);
  36044. this.update();
  36045. };
  36046. /**
  36047. * Binds this uniform buffer to an effect.
  36048. * @param {Effect} effect
  36049. * @param {string} name Name of the uniform block in the shader.
  36050. */
  36051. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36052. this._currentEffect = effect;
  36053. if (this._noUBO || !this._buffer) {
  36054. return;
  36055. }
  36056. effect.bindUniformBuffer(this._buffer, name);
  36057. };
  36058. /**
  36059. * Disposes the uniform buffer.
  36060. */
  36061. UniformBuffer.prototype.dispose = function () {
  36062. if (this._noUBO) {
  36063. return;
  36064. }
  36065. var index = this._engine._uniformBuffers.indexOf(this);
  36066. if (index !== -1) {
  36067. this._engine._uniformBuffers.splice(index, 1);
  36068. }
  36069. if (!this._buffer) {
  36070. return;
  36071. }
  36072. if (this._engine._releaseBuffer(this._buffer)) {
  36073. this._buffer = null;
  36074. }
  36075. };
  36076. // Pool for avoiding memory leaks
  36077. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36078. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36079. return UniformBuffer;
  36080. }());
  36081. BABYLON.UniformBuffer = UniformBuffer;
  36082. })(BABYLON || (BABYLON = {}));
  36083. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36084. var BABYLON;
  36085. (function (BABYLON) {
  36086. /**
  36087. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36088. */
  36089. var VertexData = /** @class */ (function () {
  36090. function VertexData() {
  36091. }
  36092. /**
  36093. * Uses the passed data array to set the set the values for the specified kind of data
  36094. * @param data a linear array of floating numbers
  36095. * @param kind the type of data that is being set, eg positions, colors etc
  36096. */
  36097. VertexData.prototype.set = function (data, kind) {
  36098. switch (kind) {
  36099. case BABYLON.VertexBuffer.PositionKind:
  36100. this.positions = data;
  36101. break;
  36102. case BABYLON.VertexBuffer.NormalKind:
  36103. this.normals = data;
  36104. break;
  36105. case BABYLON.VertexBuffer.TangentKind:
  36106. this.tangents = data;
  36107. break;
  36108. case BABYLON.VertexBuffer.UVKind:
  36109. this.uvs = data;
  36110. break;
  36111. case BABYLON.VertexBuffer.UV2Kind:
  36112. this.uvs2 = data;
  36113. break;
  36114. case BABYLON.VertexBuffer.UV3Kind:
  36115. this.uvs3 = data;
  36116. break;
  36117. case BABYLON.VertexBuffer.UV4Kind:
  36118. this.uvs4 = data;
  36119. break;
  36120. case BABYLON.VertexBuffer.UV5Kind:
  36121. this.uvs5 = data;
  36122. break;
  36123. case BABYLON.VertexBuffer.UV6Kind:
  36124. this.uvs6 = data;
  36125. break;
  36126. case BABYLON.VertexBuffer.ColorKind:
  36127. this.colors = data;
  36128. break;
  36129. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36130. this.matricesIndices = data;
  36131. break;
  36132. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36133. this.matricesWeights = data;
  36134. break;
  36135. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36136. this.matricesIndicesExtra = data;
  36137. break;
  36138. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36139. this.matricesWeightsExtra = data;
  36140. break;
  36141. }
  36142. };
  36143. /**
  36144. * Associates the vertexData to the passed Mesh.
  36145. * Sets it as updatable or not (default `false`)
  36146. * @param mesh the mesh the vertexData is applied to
  36147. * @param updatable when used and having the value true allows new data to update the vertexData
  36148. * @returns the VertexData
  36149. */
  36150. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36151. this._applyTo(mesh, updatable);
  36152. return this;
  36153. };
  36154. /**
  36155. * Associates the vertexData to the passed Geometry.
  36156. * Sets it as updatable or not (default `false`)
  36157. * @param geometry the geometry the vertexData is applied to
  36158. * @param updatable when used and having the value true allows new data to update the vertexData
  36159. * @returns VertexData
  36160. */
  36161. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36162. this._applyTo(geometry, updatable);
  36163. return this;
  36164. };
  36165. /**
  36166. * Updates the associated mesh
  36167. * @param mesh the mesh to be updated
  36168. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36169. * @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
  36170. * @returns VertexData
  36171. */
  36172. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36173. this._update(mesh);
  36174. return this;
  36175. };
  36176. /**
  36177. * Updates the associated geometry
  36178. * @param geometry the geometry to be updated
  36179. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36180. * @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
  36181. * @returns VertexData.
  36182. */
  36183. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36184. this._update(geometry);
  36185. return this;
  36186. };
  36187. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36188. if (updatable === void 0) { updatable = false; }
  36189. if (this.positions) {
  36190. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36191. }
  36192. if (this.normals) {
  36193. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36194. }
  36195. if (this.tangents) {
  36196. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36197. }
  36198. if (this.uvs) {
  36199. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36200. }
  36201. if (this.uvs2) {
  36202. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36203. }
  36204. if (this.uvs3) {
  36205. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36206. }
  36207. if (this.uvs4) {
  36208. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36209. }
  36210. if (this.uvs5) {
  36211. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36212. }
  36213. if (this.uvs6) {
  36214. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36215. }
  36216. if (this.colors) {
  36217. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36218. }
  36219. if (this.matricesIndices) {
  36220. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36221. }
  36222. if (this.matricesWeights) {
  36223. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36224. }
  36225. if (this.matricesIndicesExtra) {
  36226. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36227. }
  36228. if (this.matricesWeightsExtra) {
  36229. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36230. }
  36231. if (this.indices) {
  36232. meshOrGeometry.setIndices(this.indices, null, updatable);
  36233. }
  36234. return this;
  36235. };
  36236. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36237. if (this.positions) {
  36238. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36239. }
  36240. if (this.normals) {
  36241. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36242. }
  36243. if (this.tangents) {
  36244. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36245. }
  36246. if (this.uvs) {
  36247. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36248. }
  36249. if (this.uvs2) {
  36250. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36251. }
  36252. if (this.uvs3) {
  36253. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36254. }
  36255. if (this.uvs4) {
  36256. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36257. }
  36258. if (this.uvs5) {
  36259. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36260. }
  36261. if (this.uvs6) {
  36262. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36263. }
  36264. if (this.colors) {
  36265. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36266. }
  36267. if (this.matricesIndices) {
  36268. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36269. }
  36270. if (this.matricesWeights) {
  36271. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36272. }
  36273. if (this.matricesIndicesExtra) {
  36274. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36275. }
  36276. if (this.matricesWeightsExtra) {
  36277. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36278. }
  36279. if (this.indices) {
  36280. meshOrGeometry.setIndices(this.indices, null);
  36281. }
  36282. return this;
  36283. };
  36284. /**
  36285. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36286. * @param matrix the transforming matrix
  36287. * @returns the VertexData
  36288. */
  36289. VertexData.prototype.transform = function (matrix) {
  36290. var transformed = BABYLON.Vector3.Zero();
  36291. var index;
  36292. if (this.positions) {
  36293. var position = BABYLON.Vector3.Zero();
  36294. for (index = 0; index < this.positions.length; index += 3) {
  36295. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36296. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36297. this.positions[index] = transformed.x;
  36298. this.positions[index + 1] = transformed.y;
  36299. this.positions[index + 2] = transformed.z;
  36300. }
  36301. }
  36302. if (this.normals) {
  36303. var normal = BABYLON.Vector3.Zero();
  36304. for (index = 0; index < this.normals.length; index += 3) {
  36305. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36306. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36307. this.normals[index] = transformed.x;
  36308. this.normals[index + 1] = transformed.y;
  36309. this.normals[index + 2] = transformed.z;
  36310. }
  36311. }
  36312. if (this.tangents) {
  36313. var tangent = BABYLON.Vector4.Zero();
  36314. var tangentTransformed = BABYLON.Vector4.Zero();
  36315. for (index = 0; index < this.tangents.length; index += 4) {
  36316. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36317. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36318. this.tangents[index] = tangentTransformed.x;
  36319. this.tangents[index + 1] = tangentTransformed.y;
  36320. this.tangents[index + 2] = tangentTransformed.z;
  36321. this.tangents[index + 3] = tangentTransformed.w;
  36322. }
  36323. }
  36324. return this;
  36325. };
  36326. /**
  36327. * Merges the passed VertexData into the current one
  36328. * @param other the VertexData to be merged into the current one
  36329. * @returns the modified VertexData
  36330. */
  36331. VertexData.prototype.merge = function (other) {
  36332. this._validate();
  36333. other._validate();
  36334. if (!this.normals !== !other.normals ||
  36335. !this.tangents !== !other.tangents ||
  36336. !this.uvs !== !other.uvs ||
  36337. !this.uvs2 !== !other.uvs2 ||
  36338. !this.uvs3 !== !other.uvs3 ||
  36339. !this.uvs4 !== !other.uvs4 ||
  36340. !this.uvs5 !== !other.uvs5 ||
  36341. !this.uvs6 !== !other.uvs6 ||
  36342. !this.colors !== !other.colors ||
  36343. !this.matricesIndices !== !other.matricesIndices ||
  36344. !this.matricesWeights !== !other.matricesWeights ||
  36345. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36346. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36347. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36348. }
  36349. if (other.indices) {
  36350. if (!this.indices) {
  36351. this.indices = [];
  36352. }
  36353. var offset = this.positions ? this.positions.length / 3 : 0;
  36354. for (var index = 0; index < other.indices.length; index++) {
  36355. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36356. this.indices.push(other.indices[index] + offset);
  36357. }
  36358. }
  36359. this.positions = this._mergeElement(this.positions, other.positions);
  36360. this.normals = this._mergeElement(this.normals, other.normals);
  36361. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36362. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36363. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36364. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36365. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36366. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36367. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36368. this.colors = this._mergeElement(this.colors, other.colors);
  36369. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36370. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36371. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36372. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36373. return this;
  36374. };
  36375. VertexData.prototype._mergeElement = function (source, other) {
  36376. if (!source) {
  36377. return other;
  36378. }
  36379. if (!other) {
  36380. return source;
  36381. }
  36382. var len = other.length + source.length;
  36383. var isSrcTypedArray = source instanceof Float32Array;
  36384. var isOthTypedArray = other instanceof Float32Array;
  36385. // use non-loop method when the source is Float32Array
  36386. if (isSrcTypedArray) {
  36387. var ret32 = new Float32Array(len);
  36388. ret32.set(source);
  36389. ret32.set(other, source.length);
  36390. return ret32;
  36391. // source is number[], when other is also use concat
  36392. }
  36393. else if (!isOthTypedArray) {
  36394. return source.concat(other);
  36395. // source is a number[], but other is a Float32Array, loop required
  36396. }
  36397. else {
  36398. var ret = source.slice(0); // copy source to a separate array
  36399. for (var i = 0, len = other.length; i < len; i++) {
  36400. ret.push(other[i]);
  36401. }
  36402. return ret;
  36403. }
  36404. };
  36405. VertexData.prototype._validate = function () {
  36406. if (!this.positions) {
  36407. throw new Error("Positions are required");
  36408. }
  36409. var getElementCount = function (kind, values) {
  36410. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36411. if ((values.length % stride) !== 0) {
  36412. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36413. }
  36414. return values.length / stride;
  36415. };
  36416. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36417. var validateElementCount = function (kind, values) {
  36418. var elementCount = getElementCount(kind, values);
  36419. if (elementCount !== positionsElementCount) {
  36420. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36421. }
  36422. };
  36423. if (this.normals)
  36424. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36425. if (this.tangents)
  36426. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36427. if (this.uvs)
  36428. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36429. if (this.uvs2)
  36430. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36431. if (this.uvs3)
  36432. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36433. if (this.uvs4)
  36434. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36435. if (this.uvs5)
  36436. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36437. if (this.uvs6)
  36438. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36439. if (this.colors)
  36440. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36441. if (this.matricesIndices)
  36442. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36443. if (this.matricesWeights)
  36444. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36445. if (this.matricesIndicesExtra)
  36446. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36447. if (this.matricesWeightsExtra)
  36448. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36449. };
  36450. /**
  36451. * Serializes the VertexData
  36452. * @returns a serialized object
  36453. */
  36454. VertexData.prototype.serialize = function () {
  36455. var serializationObject = this.serialize();
  36456. if (this.positions) {
  36457. serializationObject.positions = this.positions;
  36458. }
  36459. if (this.normals) {
  36460. serializationObject.normals = this.normals;
  36461. }
  36462. if (this.tangents) {
  36463. serializationObject.tangents = this.tangents;
  36464. }
  36465. if (this.uvs) {
  36466. serializationObject.uvs = this.uvs;
  36467. }
  36468. if (this.uvs2) {
  36469. serializationObject.uvs2 = this.uvs2;
  36470. }
  36471. if (this.uvs3) {
  36472. serializationObject.uvs3 = this.uvs3;
  36473. }
  36474. if (this.uvs4) {
  36475. serializationObject.uvs4 = this.uvs4;
  36476. }
  36477. if (this.uvs5) {
  36478. serializationObject.uvs5 = this.uvs5;
  36479. }
  36480. if (this.uvs6) {
  36481. serializationObject.uvs6 = this.uvs6;
  36482. }
  36483. if (this.colors) {
  36484. serializationObject.colors = this.colors;
  36485. }
  36486. if (this.matricesIndices) {
  36487. serializationObject.matricesIndices = this.matricesIndices;
  36488. serializationObject.matricesIndices._isExpanded = true;
  36489. }
  36490. if (this.matricesWeights) {
  36491. serializationObject.matricesWeights = this.matricesWeights;
  36492. }
  36493. if (this.matricesIndicesExtra) {
  36494. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36495. serializationObject.matricesIndicesExtra._isExpanded = true;
  36496. }
  36497. if (this.matricesWeightsExtra) {
  36498. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36499. }
  36500. serializationObject.indices = this.indices;
  36501. return serializationObject;
  36502. };
  36503. // Statics
  36504. /**
  36505. * Extracts the vertexData from a mesh
  36506. * @param mesh the mesh from which to extract the VertexData
  36507. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36508. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36509. * @returns the object VertexData associated to the passed mesh
  36510. */
  36511. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36512. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36513. };
  36514. /**
  36515. * Extracts the vertexData from the geometry
  36516. * @param geometry the geometry from which to extract the VertexData
  36517. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36518. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36519. * @returns the object VertexData associated to the passed mesh
  36520. */
  36521. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36522. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36523. };
  36524. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36525. var result = new VertexData();
  36526. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36527. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36528. }
  36529. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36530. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36531. }
  36532. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36533. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36534. }
  36535. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36536. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36537. }
  36538. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36539. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36540. }
  36541. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36542. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36543. }
  36544. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36545. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36546. }
  36547. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36548. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36549. }
  36550. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36551. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36552. }
  36553. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36554. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36555. }
  36556. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36557. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36558. }
  36559. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36560. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36561. }
  36562. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36563. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36564. }
  36565. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36566. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36567. }
  36568. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36569. return result;
  36570. };
  36571. /**
  36572. * Creates the VertexData for a Ribbon
  36573. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36574. * * pathArray array of paths, each of which an array of successive Vector3
  36575. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36576. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36577. * * 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
  36578. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36579. * * 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)
  36580. * * 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)
  36581. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36582. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36583. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36584. * @returns the VertexData of the ribbon
  36585. */
  36586. VertexData.CreateRibbon = function (options) {
  36587. var pathArray = options.pathArray;
  36588. var closeArray = options.closeArray || false;
  36589. var closePath = options.closePath || false;
  36590. var invertUV = options.invertUV || false;
  36591. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36592. var offset = options.offset || defaultOffset;
  36593. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36594. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36595. var customUV = options.uvs;
  36596. var customColors = options.colors;
  36597. var positions = [];
  36598. var indices = [];
  36599. var normals = [];
  36600. var uvs = [];
  36601. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36602. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36603. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36604. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36605. var minlg; // minimal length among all paths from pathArray
  36606. var lg = []; // array of path lengths : nb of vertex per path
  36607. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36608. var p; // path iterator
  36609. var i; // point iterator
  36610. var j; // point iterator
  36611. // if single path in pathArray
  36612. if (pathArray.length < 2) {
  36613. var ar1 = [];
  36614. var ar2 = [];
  36615. for (i = 0; i < pathArray[0].length - offset; i++) {
  36616. ar1.push(pathArray[0][i]);
  36617. ar2.push(pathArray[0][i + offset]);
  36618. }
  36619. pathArray = [ar1, ar2];
  36620. }
  36621. // positions and horizontal distances (u)
  36622. var idc = 0;
  36623. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36624. var path;
  36625. var l;
  36626. minlg = pathArray[0].length;
  36627. var vectlg;
  36628. var dist;
  36629. for (p = 0; p < pathArray.length; p++) {
  36630. uTotalDistance[p] = 0;
  36631. us[p] = [0];
  36632. path = pathArray[p];
  36633. l = path.length;
  36634. minlg = (minlg < l) ? minlg : l;
  36635. j = 0;
  36636. while (j < l) {
  36637. positions.push(path[j].x, path[j].y, path[j].z);
  36638. if (j > 0) {
  36639. vectlg = path[j].subtract(path[j - 1]).length();
  36640. dist = vectlg + uTotalDistance[p];
  36641. us[p].push(dist);
  36642. uTotalDistance[p] = dist;
  36643. }
  36644. j++;
  36645. }
  36646. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36647. j--;
  36648. positions.push(path[0].x, path[0].y, path[0].z);
  36649. vectlg = path[j].subtract(path[0]).length();
  36650. dist = vectlg + uTotalDistance[p];
  36651. us[p].push(dist);
  36652. uTotalDistance[p] = dist;
  36653. }
  36654. lg[p] = l + closePathCorr;
  36655. idx[p] = idc;
  36656. idc += (l + closePathCorr);
  36657. }
  36658. // vertical distances (v)
  36659. var path1;
  36660. var path2;
  36661. var vertex1 = null;
  36662. var vertex2 = null;
  36663. for (i = 0; i < minlg + closePathCorr; i++) {
  36664. vTotalDistance[i] = 0;
  36665. vs[i] = [0];
  36666. for (p = 0; p < pathArray.length - 1; p++) {
  36667. path1 = pathArray[p];
  36668. path2 = pathArray[p + 1];
  36669. if (i === minlg) { // closePath
  36670. vertex1 = path1[0];
  36671. vertex2 = path2[0];
  36672. }
  36673. else {
  36674. vertex1 = path1[i];
  36675. vertex2 = path2[i];
  36676. }
  36677. vectlg = vertex2.subtract(vertex1).length();
  36678. dist = vectlg + vTotalDistance[i];
  36679. vs[i].push(dist);
  36680. vTotalDistance[i] = dist;
  36681. }
  36682. if (closeArray && vertex2 && vertex1) {
  36683. path1 = pathArray[p];
  36684. path2 = pathArray[0];
  36685. if (i === minlg) { // closePath
  36686. vertex2 = path2[0];
  36687. }
  36688. vectlg = vertex2.subtract(vertex1).length();
  36689. dist = vectlg + vTotalDistance[i];
  36690. vTotalDistance[i] = dist;
  36691. }
  36692. }
  36693. // uvs
  36694. var u;
  36695. var v;
  36696. if (customUV) {
  36697. for (p = 0; p < customUV.length; p++) {
  36698. uvs.push(customUV[p].x, customUV[p].y);
  36699. }
  36700. }
  36701. else {
  36702. for (p = 0; p < pathArray.length; p++) {
  36703. for (i = 0; i < minlg + closePathCorr; i++) {
  36704. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36705. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36706. if (invertUV) {
  36707. uvs.push(v, u);
  36708. }
  36709. else {
  36710. uvs.push(u, v);
  36711. }
  36712. }
  36713. }
  36714. }
  36715. // indices
  36716. p = 0; // path index
  36717. var pi = 0; // positions array index
  36718. var l1 = lg[p] - 1; // path1 length
  36719. var l2 = lg[p + 1] - 1; // path2 length
  36720. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36721. var shft = idx[1] - idx[0]; // shift
  36722. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36723. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36724. // 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
  36725. indices.push(pi, pi + shft, pi + 1);
  36726. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36727. pi += 1;
  36728. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36729. p++;
  36730. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36731. shft = idx[0] - idx[p];
  36732. l1 = lg[p] - 1;
  36733. l2 = lg[0] - 1;
  36734. }
  36735. else {
  36736. shft = idx[p + 1] - idx[p];
  36737. l1 = lg[p] - 1;
  36738. l2 = lg[p + 1] - 1;
  36739. }
  36740. pi = idx[p];
  36741. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36742. }
  36743. }
  36744. // normals
  36745. VertexData.ComputeNormals(positions, indices, normals);
  36746. if (closePath) { // update both the first and last vertex normals to their average value
  36747. var indexFirst = 0;
  36748. var indexLast = 0;
  36749. for (p = 0; p < pathArray.length; p++) {
  36750. indexFirst = idx[p] * 3;
  36751. if (p + 1 < pathArray.length) {
  36752. indexLast = (idx[p + 1] - 1) * 3;
  36753. }
  36754. else {
  36755. indexLast = normals.length - 3;
  36756. }
  36757. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36758. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36759. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36760. normals[indexLast] = normals[indexFirst];
  36761. normals[indexLast + 1] = normals[indexFirst + 1];
  36762. normals[indexLast + 2] = normals[indexFirst + 2];
  36763. }
  36764. }
  36765. // sides
  36766. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36767. // Colors
  36768. var colors = null;
  36769. if (customColors) {
  36770. colors = new Float32Array(customColors.length * 4);
  36771. for (var c = 0; c < customColors.length; c++) {
  36772. colors[c * 4] = customColors[c].r;
  36773. colors[c * 4 + 1] = customColors[c].g;
  36774. colors[c * 4 + 2] = customColors[c].b;
  36775. colors[c * 4 + 3] = customColors[c].a;
  36776. }
  36777. }
  36778. // Result
  36779. var vertexData = new VertexData();
  36780. var positions32 = new Float32Array(positions);
  36781. var normals32 = new Float32Array(normals);
  36782. var uvs32 = new Float32Array(uvs);
  36783. vertexData.indices = indices;
  36784. vertexData.positions = positions32;
  36785. vertexData.normals = normals32;
  36786. vertexData.uvs = uvs32;
  36787. if (colors) {
  36788. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36789. }
  36790. if (closePath) {
  36791. vertexData._idx = idx;
  36792. }
  36793. return vertexData;
  36794. };
  36795. /**
  36796. * Creates the VertexData for a box
  36797. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36798. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36799. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36800. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36801. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36802. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36803. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36804. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36805. * * 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)
  36806. * * 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)
  36807. * @returns the VertexData of the box
  36808. */
  36809. VertexData.CreateBox = function (options) {
  36810. var normalsSource = [
  36811. new BABYLON.Vector3(0, 0, 1),
  36812. new BABYLON.Vector3(0, 0, -1),
  36813. new BABYLON.Vector3(1, 0, 0),
  36814. new BABYLON.Vector3(-1, 0, 0),
  36815. new BABYLON.Vector3(0, 1, 0),
  36816. new BABYLON.Vector3(0, -1, 0)
  36817. ];
  36818. var indices = [];
  36819. var positions = [];
  36820. var normals = [];
  36821. var uvs = [];
  36822. var width = options.width || options.size || 1;
  36823. var height = options.height || options.size || 1;
  36824. var depth = options.depth || options.size || 1;
  36825. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36826. var faceUV = options.faceUV || new Array(6);
  36827. var faceColors = options.faceColors;
  36828. var colors = [];
  36829. // default face colors and UV if undefined
  36830. for (var f = 0; f < 6; f++) {
  36831. if (faceUV[f] === undefined) {
  36832. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36833. }
  36834. if (faceColors && faceColors[f] === undefined) {
  36835. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36836. }
  36837. }
  36838. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36839. // Create each face in turn.
  36840. for (var index = 0; index < normalsSource.length; index++) {
  36841. var normal = normalsSource[index];
  36842. // Get two vectors perpendicular to the face normal and to each other.
  36843. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36844. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36845. // Six indices (two triangles) per face.
  36846. var verticesLength = positions.length / 3;
  36847. indices.push(verticesLength);
  36848. indices.push(verticesLength + 1);
  36849. indices.push(verticesLength + 2);
  36850. indices.push(verticesLength);
  36851. indices.push(verticesLength + 2);
  36852. indices.push(verticesLength + 3);
  36853. // Four vertices per face.
  36854. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36855. positions.push(vertex.x, vertex.y, vertex.z);
  36856. normals.push(normal.x, normal.y, normal.z);
  36857. uvs.push(faceUV[index].z, faceUV[index].w);
  36858. if (faceColors) {
  36859. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36860. }
  36861. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36862. positions.push(vertex.x, vertex.y, vertex.z);
  36863. normals.push(normal.x, normal.y, normal.z);
  36864. uvs.push(faceUV[index].x, faceUV[index].w);
  36865. if (faceColors) {
  36866. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36867. }
  36868. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36869. positions.push(vertex.x, vertex.y, vertex.z);
  36870. normals.push(normal.x, normal.y, normal.z);
  36871. uvs.push(faceUV[index].x, faceUV[index].y);
  36872. if (faceColors) {
  36873. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36874. }
  36875. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36876. positions.push(vertex.x, vertex.y, vertex.z);
  36877. normals.push(normal.x, normal.y, normal.z);
  36878. uvs.push(faceUV[index].z, faceUV[index].y);
  36879. if (faceColors) {
  36880. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36881. }
  36882. }
  36883. // sides
  36884. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36885. // Result
  36886. var vertexData = new VertexData();
  36887. vertexData.indices = indices;
  36888. vertexData.positions = positions;
  36889. vertexData.normals = normals;
  36890. vertexData.uvs = uvs;
  36891. if (faceColors) {
  36892. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36893. vertexData.colors = totalColors;
  36894. }
  36895. return vertexData;
  36896. };
  36897. /**
  36898. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36899. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36900. * * segments sets the number of horizontal strips optional, default 32
  36901. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36902. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36903. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36904. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36905. * * 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
  36906. * * 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
  36907. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36908. * * 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)
  36909. * * 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)
  36910. * @returns the VertexData of the ellipsoid
  36911. */
  36912. VertexData.CreateSphere = function (options) {
  36913. var segments = options.segments || 32;
  36914. var diameterX = options.diameterX || options.diameter || 1;
  36915. var diameterY = options.diameterY || options.diameter || 1;
  36916. var diameterZ = options.diameterZ || options.diameter || 1;
  36917. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36918. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36919. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36920. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36921. var totalZRotationSteps = 2 + segments;
  36922. var totalYRotationSteps = 2 * totalZRotationSteps;
  36923. var indices = [];
  36924. var positions = [];
  36925. var normals = [];
  36926. var uvs = [];
  36927. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36928. var normalizedZ = zRotationStep / totalZRotationSteps;
  36929. var angleZ = normalizedZ * Math.PI * slice;
  36930. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36931. var normalizedY = yRotationStep / totalYRotationSteps;
  36932. var angleY = normalizedY * Math.PI * 2 * arc;
  36933. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36934. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36935. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36936. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36937. var vertex = complete.multiply(radius);
  36938. var normal = complete.divide(radius).normalize();
  36939. positions.push(vertex.x, vertex.y, vertex.z);
  36940. normals.push(normal.x, normal.y, normal.z);
  36941. uvs.push(normalizedY, normalizedZ);
  36942. }
  36943. if (zRotationStep > 0) {
  36944. var verticesCount = positions.length / 3;
  36945. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36946. indices.push((firstIndex));
  36947. indices.push((firstIndex + 1));
  36948. indices.push(firstIndex + totalYRotationSteps + 1);
  36949. indices.push((firstIndex + totalYRotationSteps + 1));
  36950. indices.push((firstIndex + 1));
  36951. indices.push((firstIndex + totalYRotationSteps + 2));
  36952. }
  36953. }
  36954. }
  36955. // Sides
  36956. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36957. // Result
  36958. var vertexData = new VertexData();
  36959. vertexData.indices = indices;
  36960. vertexData.positions = positions;
  36961. vertexData.normals = normals;
  36962. vertexData.uvs = uvs;
  36963. return vertexData;
  36964. };
  36965. /**
  36966. * Creates the VertexData for a cylinder, cone or prism
  36967. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36968. * * height sets the height (y direction) of the cylinder, optional, default 2
  36969. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36970. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36971. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36972. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36973. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36974. * * 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
  36975. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36976. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36977. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36978. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36979. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36980. * * 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)
  36981. * * 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)
  36982. * @returns the VertexData of the cylinder, cone or prism
  36983. */
  36984. VertexData.CreateCylinder = function (options) {
  36985. var height = options.height || 2;
  36986. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36987. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36988. var tessellation = options.tessellation || 24;
  36989. var subdivisions = options.subdivisions || 1;
  36990. var hasRings = options.hasRings ? true : false;
  36991. var enclose = options.enclose ? true : false;
  36992. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36993. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36994. var faceUV = options.faceUV || new Array(3);
  36995. var faceColors = options.faceColors;
  36996. // default face colors and UV if undefined
  36997. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36998. var ringNb = (hasRings) ? subdivisions : 1;
  36999. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37000. var f;
  37001. for (f = 0; f < surfaceNb; f++) {
  37002. if (faceColors && faceColors[f] === undefined) {
  37003. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37004. }
  37005. }
  37006. for (f = 0; f < surfaceNb; f++) {
  37007. if (faceUV && faceUV[f] === undefined) {
  37008. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37009. }
  37010. }
  37011. var indices = new Array();
  37012. var positions = new Array();
  37013. var normals = new Array();
  37014. var uvs = new Array();
  37015. var colors = new Array();
  37016. var angle_step = Math.PI * 2 * arc / tessellation;
  37017. var angle;
  37018. var h;
  37019. var radius;
  37020. var tan = (diameterBottom - diameterTop) / 2 / height;
  37021. var ringVertex = BABYLON.Vector3.Zero();
  37022. var ringNormal = BABYLON.Vector3.Zero();
  37023. var ringFirstVertex = BABYLON.Vector3.Zero();
  37024. var ringFirstNormal = BABYLON.Vector3.Zero();
  37025. var quadNormal = BABYLON.Vector3.Zero();
  37026. var Y = BABYLON.Axis.Y;
  37027. // positions, normals, uvs
  37028. var i;
  37029. var j;
  37030. var r;
  37031. var ringIdx = 1;
  37032. var s = 1; // surface index
  37033. var cs = 0;
  37034. var v = 0;
  37035. for (i = 0; i <= subdivisions; i++) {
  37036. h = i / subdivisions;
  37037. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37038. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37039. for (r = 0; r < ringIdx; r++) {
  37040. if (hasRings) {
  37041. s += r;
  37042. }
  37043. if (enclose) {
  37044. s += 2 * r;
  37045. }
  37046. for (j = 0; j <= tessellation; j++) {
  37047. angle = j * angle_step;
  37048. // position
  37049. ringVertex.x = Math.cos(-angle) * radius;
  37050. ringVertex.y = -height / 2 + h * height;
  37051. ringVertex.z = Math.sin(-angle) * radius;
  37052. // normal
  37053. if (diameterTop === 0 && i === subdivisions) {
  37054. // if no top cap, reuse former normals
  37055. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37056. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37057. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37058. }
  37059. else {
  37060. ringNormal.x = ringVertex.x;
  37061. ringNormal.z = ringVertex.z;
  37062. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37063. ringNormal.normalize();
  37064. }
  37065. // keep first ring vertex values for enclose
  37066. if (j === 0) {
  37067. ringFirstVertex.copyFrom(ringVertex);
  37068. ringFirstNormal.copyFrom(ringNormal);
  37069. }
  37070. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37071. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37072. if (hasRings) {
  37073. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37074. }
  37075. else {
  37076. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37077. }
  37078. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37079. if (faceColors) {
  37080. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37081. }
  37082. }
  37083. // if enclose, add four vertices and their dedicated normals
  37084. if (arc !== 1 && enclose) {
  37085. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37086. positions.push(0, ringVertex.y, 0);
  37087. positions.push(0, ringVertex.y, 0);
  37088. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37089. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37090. quadNormal.normalize();
  37091. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37092. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37093. quadNormal.normalize();
  37094. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37095. if (hasRings) {
  37096. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37097. }
  37098. else {
  37099. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37100. }
  37101. uvs.push(faceUV[s + 1].x, v);
  37102. uvs.push(faceUV[s + 1].z, v);
  37103. if (hasRings) {
  37104. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37105. }
  37106. else {
  37107. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37108. }
  37109. uvs.push(faceUV[s + 2].x, v);
  37110. uvs.push(faceUV[s + 2].z, v);
  37111. if (faceColors) {
  37112. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37113. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37114. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37115. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37116. }
  37117. }
  37118. if (cs !== s) {
  37119. cs = s;
  37120. }
  37121. }
  37122. }
  37123. // indices
  37124. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37125. var s;
  37126. i = 0;
  37127. for (s = 0; s < subdivisions; s++) {
  37128. var i0 = 0;
  37129. var i1 = 0;
  37130. var i2 = 0;
  37131. var i3 = 0;
  37132. for (j = 0; j < tessellation; j++) {
  37133. i0 = i * (e + 1) + j;
  37134. i1 = (i + 1) * (e + 1) + j;
  37135. i2 = i * (e + 1) + (j + 1);
  37136. i3 = (i + 1) * (e + 1) + (j + 1);
  37137. indices.push(i0, i1, i2);
  37138. indices.push(i3, i2, i1);
  37139. }
  37140. if (arc !== 1 && enclose) { // if enclose, add two quads
  37141. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37142. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37143. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37144. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37145. }
  37146. i = (hasRings) ? (i + 2) : (i + 1);
  37147. }
  37148. // Caps
  37149. var createCylinderCap = function (isTop) {
  37150. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37151. if (radius === 0) {
  37152. return;
  37153. }
  37154. // Cap positions, normals & uvs
  37155. var angle;
  37156. var circleVector;
  37157. var i;
  37158. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37159. var c = null;
  37160. if (faceColors) {
  37161. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37162. }
  37163. // cap center
  37164. var vbase = positions.length / 3;
  37165. var offset = isTop ? height / 2 : -height / 2;
  37166. var center = new BABYLON.Vector3(0, offset, 0);
  37167. positions.push(center.x, center.y, center.z);
  37168. normals.push(0, isTop ? 1 : -1, 0);
  37169. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37170. if (c) {
  37171. colors.push(c.r, c.g, c.b, c.a);
  37172. }
  37173. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37174. for (i = 0; i <= tessellation; i++) {
  37175. angle = Math.PI * 2 * i * arc / tessellation;
  37176. var cos = Math.cos(-angle);
  37177. var sin = Math.sin(-angle);
  37178. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37179. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37180. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37181. normals.push(0, isTop ? 1 : -1, 0);
  37182. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37183. if (c) {
  37184. colors.push(c.r, c.g, c.b, c.a);
  37185. }
  37186. }
  37187. // Cap indices
  37188. for (i = 0; i < tessellation; i++) {
  37189. if (!isTop) {
  37190. indices.push(vbase);
  37191. indices.push(vbase + (i + 1));
  37192. indices.push(vbase + (i + 2));
  37193. }
  37194. else {
  37195. indices.push(vbase);
  37196. indices.push(vbase + (i + 2));
  37197. indices.push(vbase + (i + 1));
  37198. }
  37199. }
  37200. };
  37201. // add caps to geometry
  37202. createCylinderCap(false);
  37203. createCylinderCap(true);
  37204. // Sides
  37205. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37206. var vertexData = new VertexData();
  37207. vertexData.indices = indices;
  37208. vertexData.positions = positions;
  37209. vertexData.normals = normals;
  37210. vertexData.uvs = uvs;
  37211. if (faceColors) {
  37212. vertexData.colors = colors;
  37213. }
  37214. return vertexData;
  37215. };
  37216. /**
  37217. * Creates the VertexData for a torus
  37218. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37219. * * diameter the diameter of the torus, optional default 1
  37220. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37221. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37222. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37223. * * 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)
  37224. * * 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)
  37225. * @returns the VertexData of the torus
  37226. */
  37227. VertexData.CreateTorus = function (options) {
  37228. var indices = [];
  37229. var positions = [];
  37230. var normals = [];
  37231. var uvs = [];
  37232. var diameter = options.diameter || 1;
  37233. var thickness = options.thickness || 0.5;
  37234. var tessellation = options.tessellation || 16;
  37235. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37236. var stride = tessellation + 1;
  37237. for (var i = 0; i <= tessellation; i++) {
  37238. var u = i / tessellation;
  37239. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37240. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37241. for (var j = 0; j <= tessellation; j++) {
  37242. var v = 1 - j / tessellation;
  37243. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37244. var dx = Math.cos(innerAngle);
  37245. var dy = Math.sin(innerAngle);
  37246. // Create a vertex.
  37247. var normal = new BABYLON.Vector3(dx, dy, 0);
  37248. var position = normal.scale(thickness / 2);
  37249. var textureCoordinate = new BABYLON.Vector2(u, v);
  37250. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37251. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37252. positions.push(position.x, position.y, position.z);
  37253. normals.push(normal.x, normal.y, normal.z);
  37254. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37255. // And create indices for two triangles.
  37256. var nextI = (i + 1) % stride;
  37257. var nextJ = (j + 1) % stride;
  37258. indices.push(i * stride + j);
  37259. indices.push(i * stride + nextJ);
  37260. indices.push(nextI * stride + j);
  37261. indices.push(i * stride + nextJ);
  37262. indices.push(nextI * stride + nextJ);
  37263. indices.push(nextI * stride + j);
  37264. }
  37265. }
  37266. // Sides
  37267. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37268. // Result
  37269. var vertexData = new VertexData();
  37270. vertexData.indices = indices;
  37271. vertexData.positions = positions;
  37272. vertexData.normals = normals;
  37273. vertexData.uvs = uvs;
  37274. return vertexData;
  37275. };
  37276. /**
  37277. * Creates the VertexData of the LineSystem
  37278. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37279. * - lines an array of lines, each line being an array of successive Vector3
  37280. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37281. * @returns the VertexData of the LineSystem
  37282. */
  37283. VertexData.CreateLineSystem = function (options) {
  37284. var indices = [];
  37285. var positions = [];
  37286. var lines = options.lines;
  37287. var colors = options.colors;
  37288. var vertexColors = [];
  37289. var idx = 0;
  37290. for (var l = 0; l < lines.length; l++) {
  37291. var points = lines[l];
  37292. for (var index = 0; index < points.length; index++) {
  37293. positions.push(points[index].x, points[index].y, points[index].z);
  37294. if (colors) {
  37295. var color = colors[l];
  37296. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37297. }
  37298. if (index > 0) {
  37299. indices.push(idx - 1);
  37300. indices.push(idx);
  37301. }
  37302. idx++;
  37303. }
  37304. }
  37305. var vertexData = new VertexData();
  37306. vertexData.indices = indices;
  37307. vertexData.positions = positions;
  37308. if (colors) {
  37309. vertexData.colors = vertexColors;
  37310. }
  37311. return vertexData;
  37312. };
  37313. /**
  37314. * Create the VertexData for a DashedLines
  37315. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37316. * - points an array successive Vector3
  37317. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37318. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37319. * - dashNb the intended total number of dashes, optional, default 200
  37320. * @returns the VertexData for the DashedLines
  37321. */
  37322. VertexData.CreateDashedLines = function (options) {
  37323. var dashSize = options.dashSize || 3;
  37324. var gapSize = options.gapSize || 1;
  37325. var dashNb = options.dashNb || 200;
  37326. var points = options.points;
  37327. var positions = new Array();
  37328. var indices = new Array();
  37329. var curvect = BABYLON.Vector3.Zero();
  37330. var lg = 0;
  37331. var nb = 0;
  37332. var shft = 0;
  37333. var dashshft = 0;
  37334. var curshft = 0;
  37335. var idx = 0;
  37336. var i = 0;
  37337. for (i = 0; i < points.length - 1; i++) {
  37338. points[i + 1].subtractToRef(points[i], curvect);
  37339. lg += curvect.length();
  37340. }
  37341. shft = lg / dashNb;
  37342. dashshft = dashSize * shft / (dashSize + gapSize);
  37343. for (i = 0; i < points.length - 1; i++) {
  37344. points[i + 1].subtractToRef(points[i], curvect);
  37345. nb = Math.floor(curvect.length() / shft);
  37346. curvect.normalize();
  37347. for (var j = 0; j < nb; j++) {
  37348. curshft = shft * j;
  37349. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37350. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37351. indices.push(idx, idx + 1);
  37352. idx += 2;
  37353. }
  37354. }
  37355. // Result
  37356. var vertexData = new VertexData();
  37357. vertexData.positions = positions;
  37358. vertexData.indices = indices;
  37359. return vertexData;
  37360. };
  37361. /**
  37362. * Creates the VertexData for a Ground
  37363. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37364. * - width the width (x direction) of the ground, optional, default 1
  37365. * - height the height (z direction) of the ground, optional, default 1
  37366. * - subdivisions the number of subdivisions per side, optional, default 1
  37367. * @returns the VertexData of the Ground
  37368. */
  37369. VertexData.CreateGround = function (options) {
  37370. var indices = [];
  37371. var positions = [];
  37372. var normals = [];
  37373. var uvs = [];
  37374. var row, col;
  37375. var width = options.width || 1;
  37376. var height = options.height || 1;
  37377. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37378. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37379. for (row = 0; row <= subdivisionsY; row++) {
  37380. for (col = 0; col <= subdivisionsX; col++) {
  37381. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37382. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37383. positions.push(position.x, position.y, position.z);
  37384. normals.push(normal.x, normal.y, normal.z);
  37385. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37386. }
  37387. }
  37388. for (row = 0; row < subdivisionsY; row++) {
  37389. for (col = 0; col < subdivisionsX; col++) {
  37390. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37391. indices.push(col + 1 + row * (subdivisionsX + 1));
  37392. indices.push(col + row * (subdivisionsX + 1));
  37393. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37394. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37395. indices.push(col + row * (subdivisionsX + 1));
  37396. }
  37397. }
  37398. // Result
  37399. var vertexData = new VertexData();
  37400. vertexData.indices = indices;
  37401. vertexData.positions = positions;
  37402. vertexData.normals = normals;
  37403. vertexData.uvs = uvs;
  37404. return vertexData;
  37405. };
  37406. /**
  37407. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37408. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37409. * * xmin the ground minimum X coordinate, optional, default -1
  37410. * * zmin the ground minimum Z coordinate, optional, default -1
  37411. * * xmax the ground maximum X coordinate, optional, default 1
  37412. * * zmax the ground maximum Z coordinate, optional, default 1
  37413. * * 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}
  37414. * * 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}
  37415. * @returns the VertexData of the TiledGround
  37416. */
  37417. VertexData.CreateTiledGround = function (options) {
  37418. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37419. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37420. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37421. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37422. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37423. var precision = options.precision || { w: 1, h: 1 };
  37424. var indices = new Array();
  37425. var positions = new Array();
  37426. var normals = new Array();
  37427. var uvs = new Array();
  37428. var row, col, tileRow, tileCol;
  37429. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37430. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37431. precision.w = (precision.w < 1) ? 1 : precision.w;
  37432. precision.h = (precision.h < 1) ? 1 : precision.h;
  37433. var tileSize = {
  37434. 'w': (xmax - xmin) / subdivisions.w,
  37435. 'h': (zmax - zmin) / subdivisions.h
  37436. };
  37437. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37438. // Indices
  37439. var base = positions.length / 3;
  37440. var rowLength = precision.w + 1;
  37441. for (row = 0; row < precision.h; row++) {
  37442. for (col = 0; col < precision.w; col++) {
  37443. var square = [
  37444. base + col + row * rowLength,
  37445. base + (col + 1) + row * rowLength,
  37446. base + (col + 1) + (row + 1) * rowLength,
  37447. base + col + (row + 1) * rowLength
  37448. ];
  37449. indices.push(square[1]);
  37450. indices.push(square[2]);
  37451. indices.push(square[3]);
  37452. indices.push(square[0]);
  37453. indices.push(square[1]);
  37454. indices.push(square[3]);
  37455. }
  37456. }
  37457. // Position, normals and uvs
  37458. var position = BABYLON.Vector3.Zero();
  37459. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37460. for (row = 0; row <= precision.h; row++) {
  37461. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37462. for (col = 0; col <= precision.w; col++) {
  37463. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37464. position.y = 0;
  37465. positions.push(position.x, position.y, position.z);
  37466. normals.push(normal.x, normal.y, normal.z);
  37467. uvs.push(col / precision.w, row / precision.h);
  37468. }
  37469. }
  37470. }
  37471. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37472. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37473. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37474. }
  37475. }
  37476. // Result
  37477. var vertexData = new VertexData();
  37478. vertexData.indices = indices;
  37479. vertexData.positions = positions;
  37480. vertexData.normals = normals;
  37481. vertexData.uvs = uvs;
  37482. return vertexData;
  37483. };
  37484. /**
  37485. * Creates the VertexData of the Ground designed from a heightmap
  37486. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37487. * * width the width (x direction) of the ground
  37488. * * height the height (z direction) of the ground
  37489. * * subdivisions the number of subdivisions per side
  37490. * * minHeight the minimum altitude on the ground, optional, default 0
  37491. * * maxHeight the maximum altitude on the ground, optional default 1
  37492. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37493. * * buffer the array holding the image color data
  37494. * * bufferWidth the width of image
  37495. * * bufferHeight the height of image
  37496. * @returns the VertexData of the Ground designed from a heightmap
  37497. */
  37498. VertexData.CreateGroundFromHeightMap = function (options) {
  37499. var indices = [];
  37500. var positions = [];
  37501. var normals = [];
  37502. var uvs = [];
  37503. var row, col;
  37504. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37505. // Vertices
  37506. for (row = 0; row <= options.subdivisions; row++) {
  37507. for (col = 0; col <= options.subdivisions; col++) {
  37508. 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));
  37509. // Compute height
  37510. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37511. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37512. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37513. var r = options.buffer[pos] / 255.0;
  37514. var g = options.buffer[pos + 1] / 255.0;
  37515. var b = options.buffer[pos + 2] / 255.0;
  37516. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37517. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37518. // Add vertex
  37519. positions.push(position.x, position.y, position.z);
  37520. normals.push(0, 0, 0);
  37521. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37522. }
  37523. }
  37524. // Indices
  37525. for (row = 0; row < options.subdivisions; row++) {
  37526. for (col = 0; col < options.subdivisions; col++) {
  37527. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37528. indices.push(col + 1 + row * (options.subdivisions + 1));
  37529. indices.push(col + row * (options.subdivisions + 1));
  37530. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37531. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37532. indices.push(col + row * (options.subdivisions + 1));
  37533. }
  37534. }
  37535. // Normals
  37536. VertexData.ComputeNormals(positions, indices, normals);
  37537. // Result
  37538. var vertexData = new VertexData();
  37539. vertexData.indices = indices;
  37540. vertexData.positions = positions;
  37541. vertexData.normals = normals;
  37542. vertexData.uvs = uvs;
  37543. return vertexData;
  37544. };
  37545. /**
  37546. * Creates the VertexData for a Plane
  37547. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37548. * * size sets the width and height of the plane to the value of size, optional default 1
  37549. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37550. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37551. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37552. * * 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)
  37553. * * 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)
  37554. * @returns the VertexData of the box
  37555. */
  37556. VertexData.CreatePlane = function (options) {
  37557. var indices = [];
  37558. var positions = [];
  37559. var normals = [];
  37560. var uvs = [];
  37561. var width = options.width || options.size || 1;
  37562. var height = options.height || options.size || 1;
  37563. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37564. // Vertices
  37565. var halfWidth = width / 2.0;
  37566. var halfHeight = height / 2.0;
  37567. positions.push(-halfWidth, -halfHeight, 0);
  37568. normals.push(0, 0, -1.0);
  37569. uvs.push(0.0, 0.0);
  37570. positions.push(halfWidth, -halfHeight, 0);
  37571. normals.push(0, 0, -1.0);
  37572. uvs.push(1.0, 0.0);
  37573. positions.push(halfWidth, halfHeight, 0);
  37574. normals.push(0, 0, -1.0);
  37575. uvs.push(1.0, 1.0);
  37576. positions.push(-halfWidth, halfHeight, 0);
  37577. normals.push(0, 0, -1.0);
  37578. uvs.push(0.0, 1.0);
  37579. // Indices
  37580. indices.push(0);
  37581. indices.push(1);
  37582. indices.push(2);
  37583. indices.push(0);
  37584. indices.push(2);
  37585. indices.push(3);
  37586. // Sides
  37587. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37588. // Result
  37589. var vertexData = new VertexData();
  37590. vertexData.indices = indices;
  37591. vertexData.positions = positions;
  37592. vertexData.normals = normals;
  37593. vertexData.uvs = uvs;
  37594. return vertexData;
  37595. };
  37596. /**
  37597. * Creates the VertexData of the Disc or regular Polygon
  37598. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37599. * * radius the radius of the disc, optional default 0.5
  37600. * * tessellation the number of polygon sides, optional, default 64
  37601. * * 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
  37602. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37603. * * 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)
  37604. * * 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)
  37605. * @returns the VertexData of the box
  37606. */
  37607. VertexData.CreateDisc = function (options) {
  37608. var positions = new Array();
  37609. var indices = new Array();
  37610. var normals = new Array();
  37611. var uvs = new Array();
  37612. var radius = options.radius || 0.5;
  37613. var tessellation = options.tessellation || 64;
  37614. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37615. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37616. // positions and uvs
  37617. positions.push(0, 0, 0); // disc center first
  37618. uvs.push(0.5, 0.5);
  37619. var theta = Math.PI * 2 * arc;
  37620. var step = theta / tessellation;
  37621. for (var a = 0; a < theta; a += step) {
  37622. var x = Math.cos(a);
  37623. var y = Math.sin(a);
  37624. var u = (x + 1) / 2;
  37625. var v = (1 - y) / 2;
  37626. positions.push(radius * x, radius * y, 0);
  37627. uvs.push(u, v);
  37628. }
  37629. if (arc === 1) {
  37630. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37631. uvs.push(uvs[2], uvs[3]);
  37632. }
  37633. //indices
  37634. var vertexNb = positions.length / 3;
  37635. for (var i = 1; i < vertexNb - 1; i++) {
  37636. indices.push(i + 1, 0, i);
  37637. }
  37638. // result
  37639. VertexData.ComputeNormals(positions, indices, normals);
  37640. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37641. var vertexData = new VertexData();
  37642. vertexData.indices = indices;
  37643. vertexData.positions = positions;
  37644. vertexData.normals = normals;
  37645. vertexData.uvs = uvs;
  37646. return vertexData;
  37647. };
  37648. /**
  37649. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37650. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37651. * @param polygon a mesh built from polygonTriangulation.build()
  37652. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37653. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37654. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37655. * @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)
  37656. * @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)
  37657. * @returns the VertexData of the Polygon
  37658. */
  37659. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37660. var faceUV = fUV || new Array(3);
  37661. var faceColors = fColors;
  37662. var colors = [];
  37663. // default face colors and UV if undefined
  37664. for (var f = 0; f < 3; f++) {
  37665. if (faceUV[f] === undefined) {
  37666. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37667. }
  37668. if (faceColors && faceColors[f] === undefined) {
  37669. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37670. }
  37671. }
  37672. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37673. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37674. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37675. var indices = polygon.getIndices();
  37676. // set face colours and textures
  37677. var idx = 0;
  37678. var face = 0;
  37679. for (var index = 0; index < normals.length; index += 3) {
  37680. //Edge Face no. 1
  37681. if (Math.abs(normals[index + 1]) < 0.001) {
  37682. face = 1;
  37683. }
  37684. //Top Face no. 0
  37685. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37686. face = 0;
  37687. }
  37688. //Bottom Face no. 2
  37689. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37690. face = 2;
  37691. }
  37692. idx = index / 3;
  37693. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37694. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37695. if (faceColors) {
  37696. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37697. }
  37698. }
  37699. // sides
  37700. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37701. // Result
  37702. var vertexData = new VertexData();
  37703. vertexData.indices = indices;
  37704. vertexData.positions = positions;
  37705. vertexData.normals = normals;
  37706. vertexData.uvs = uvs;
  37707. if (faceColors) {
  37708. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37709. vertexData.colors = totalColors;
  37710. }
  37711. return vertexData;
  37712. };
  37713. /**
  37714. * Creates the VertexData of the IcoSphere
  37715. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37716. * * radius the radius of the IcoSphere, optional default 1
  37717. * * radiusX allows stretching in the x direction, optional, default radius
  37718. * * radiusY allows stretching in the y direction, optional, default radius
  37719. * * radiusZ allows stretching in the z direction, optional, default radius
  37720. * * flat when true creates a flat shaded mesh, optional, default true
  37721. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37722. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37723. * * 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)
  37724. * * 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)
  37725. * @returns the VertexData of the IcoSphere
  37726. */
  37727. VertexData.CreateIcoSphere = function (options) {
  37728. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37729. var radius = options.radius || 1;
  37730. var flat = (options.flat === undefined) ? true : options.flat;
  37731. var subdivisions = options.subdivisions || 4;
  37732. var radiusX = options.radiusX || radius;
  37733. var radiusY = options.radiusY || radius;
  37734. var radiusZ = options.radiusZ || radius;
  37735. var t = (1 + Math.sqrt(5)) / 2;
  37736. // 12 vertex x,y,z
  37737. var ico_vertices = [
  37738. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37739. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37740. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37741. ];
  37742. // index of 3 vertex makes a face of icopshere
  37743. var ico_indices = [
  37744. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37745. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37746. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37747. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37748. ];
  37749. // vertex for uv have aliased position, not for UV
  37750. var vertices_unalias_id = [
  37751. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37752. // vertex alias
  37753. 0,
  37754. 2,
  37755. 3,
  37756. 3,
  37757. 3,
  37758. 4,
  37759. 7,
  37760. 8,
  37761. 9,
  37762. 9,
  37763. 10,
  37764. 11 // 23: B + 12
  37765. ];
  37766. // uv as integer step (not pixels !)
  37767. var ico_vertexuv = [
  37768. 5, 1, 3, 1, 6, 4, 0, 0,
  37769. 5, 3, 4, 2, 2, 2, 4, 0,
  37770. 2, 0, 1, 1, 6, 0, 6, 2,
  37771. // vertex alias (for same vertex on different faces)
  37772. 0, 4,
  37773. 3, 3,
  37774. 4, 4,
  37775. 3, 1,
  37776. 4, 2,
  37777. 4, 4,
  37778. 0, 2,
  37779. 1, 1,
  37780. 2, 2,
  37781. 3, 3,
  37782. 1, 3,
  37783. 2, 4 // 23: B + 12
  37784. ];
  37785. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37786. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37787. // First island of uv mapping
  37788. // v = 4h 3+ 2
  37789. // v = 3h 9+ 4
  37790. // v = 2h 9+ 5 B
  37791. // v = 1h 9 1 0
  37792. // v = 0h 3 8 7 A
  37793. // u = 0 1 2 3 4 5 6 *a
  37794. // Second island of uv mapping
  37795. // v = 4h 0+ B+ 4+
  37796. // v = 3h A+ 2+
  37797. // v = 2h 7+ 6 3+
  37798. // v = 1h 8+ 3+
  37799. // v = 0h
  37800. // u = 0 1 2 3 4 5 6 *a
  37801. // Face layout on texture UV mapping
  37802. // ============
  37803. // \ 4 /\ 16 / ======
  37804. // \ / \ / /\ 11 /
  37805. // \/ 7 \/ / \ /
  37806. // ======= / 10 \/
  37807. // /\ 17 /\ =======
  37808. // / \ / \ \ 15 /\
  37809. // / 8 \/ 12 \ \ / \
  37810. // ============ \/ 6 \
  37811. // \ 18 /\ ============
  37812. // \ / \ \ 5 /\ 0 /
  37813. // \/ 13 \ \ / \ /
  37814. // ======= \/ 1 \/
  37815. // =============
  37816. // /\ 19 /\ 2 /\
  37817. // / \ / \ / \
  37818. // / 14 \/ 9 \/ 3 \
  37819. // ===================
  37820. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37821. var ustep = 138 / 1024;
  37822. var vstep = 239 / 1024;
  37823. var uoffset = 60 / 1024;
  37824. var voffset = 26 / 1024;
  37825. // Second island should have margin, not to touch the first island
  37826. // avoid any borderline artefact in pixel rounding
  37827. var island_u_offset = -40 / 1024;
  37828. var island_v_offset = +20 / 1024;
  37829. // face is either island 0 or 1 :
  37830. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37831. var island = [
  37832. 0, 0, 0, 0, 1,
  37833. 0, 0, 1, 1, 0,
  37834. 0, 0, 1, 1, 0,
  37835. 0, 1, 1, 1, 0 // 15 - 19
  37836. ];
  37837. var indices = new Array();
  37838. var positions = new Array();
  37839. var normals = new Array();
  37840. var uvs = new Array();
  37841. var current_indice = 0;
  37842. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37843. var face_vertex_pos = new Array(3);
  37844. var face_vertex_uv = new Array(3);
  37845. var v012;
  37846. for (v012 = 0; v012 < 3; v012++) {
  37847. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37848. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37849. }
  37850. // create all with normals
  37851. for (var face = 0; face < 20; face++) {
  37852. // 3 vertex per face
  37853. for (v012 = 0; v012 < 3; v012++) {
  37854. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37855. var v_id = ico_indices[3 * face + v012];
  37856. // vertex have 3D position (x,y,z)
  37857. 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]);
  37858. // Normalize to get normal, then scale to radius
  37859. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37860. // uv Coordinates from vertex ID
  37861. 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);
  37862. }
  37863. // Subdivide the face (interpolate pos, norm, uv)
  37864. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37865. // - norm is linear interpolation of vertex corner normal
  37866. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37867. // - uv is linear interpolation
  37868. //
  37869. // Topology is as below for sub-divide by 2
  37870. // vertex shown as v0,v1,v2
  37871. // interp index is i1 to progress in range [v0,v1[
  37872. // interp index is i2 to progress in range [v0,v2[
  37873. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37874. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37875. //
  37876. //
  37877. // i2 v2
  37878. // ^ ^
  37879. // / / \
  37880. // / / \
  37881. // / / \
  37882. // / / (0,1) \
  37883. // / #---------\
  37884. // / / \ (0,0)'/ \
  37885. // / / \ / \
  37886. // / / \ / \
  37887. // / / (0,0) \ / (1,0) \
  37888. // / #---------#---------\
  37889. // v0 v1
  37890. //
  37891. // --------------------> i1
  37892. //
  37893. // interp of (i1,i2):
  37894. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37895. // along i1 : lerp(x0,x1, i1/(S-i2))
  37896. //
  37897. // centroid of triangle is needed to get help normal computation
  37898. // (c1,c2) are used for centroid location
  37899. var interp_vertex = function (i1, i2, c1, c2) {
  37900. // vertex is interpolated from
  37901. // - face_vertex_pos[0..2]
  37902. // - face_vertex_uv[0..2]
  37903. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37904. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37905. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37906. pos_interp.normalize();
  37907. var vertex_normal;
  37908. if (flat) {
  37909. // in flat mode, recalculate normal as face centroid normal
  37910. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37911. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37912. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37913. }
  37914. else {
  37915. // in smooth mode, recalculate normal from each single vertex position
  37916. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37917. }
  37918. // Vertex normal need correction due to X,Y,Z radius scaling
  37919. vertex_normal.x /= radiusX;
  37920. vertex_normal.y /= radiusY;
  37921. vertex_normal.z /= radiusZ;
  37922. vertex_normal.normalize();
  37923. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37924. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37925. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37926. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37927. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37928. uvs.push(uv_interp.x, uv_interp.y);
  37929. // push each vertex has member of a face
  37930. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37931. indices.push(current_indice);
  37932. current_indice++;
  37933. };
  37934. for (var i2 = 0; i2 < subdivisions; i2++) {
  37935. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37936. // face : (i1,i2) for /\ :
  37937. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37938. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37939. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37940. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37941. if (i1 + i2 + 1 < subdivisions) {
  37942. // face : (i1,i2)' for \/ :
  37943. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37944. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37945. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37946. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37947. }
  37948. }
  37949. }
  37950. }
  37951. // Sides
  37952. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37953. // Result
  37954. var vertexData = new VertexData();
  37955. vertexData.indices = indices;
  37956. vertexData.positions = positions;
  37957. vertexData.normals = normals;
  37958. vertexData.uvs = uvs;
  37959. return vertexData;
  37960. };
  37961. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37962. /**
  37963. * Creates the VertexData for a Polyhedron
  37964. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37965. * * type provided types are:
  37966. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37967. * * 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)
  37968. * * size the size of the IcoSphere, optional default 1
  37969. * * sizeX allows stretching in the x direction, optional, default size
  37970. * * sizeY allows stretching in the y direction, optional, default size
  37971. * * sizeZ allows stretching in the z direction, optional, default size
  37972. * * 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
  37973. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37974. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37975. * * flat when true creates a flat shaded mesh, optional, default true
  37976. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37977. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37978. * * 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)
  37979. * * 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)
  37980. * @returns the VertexData of the Polyhedron
  37981. */
  37982. VertexData.CreatePolyhedron = function (options) {
  37983. // provided polyhedron types :
  37984. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37985. // 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)
  37986. var polyhedra = [];
  37987. 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]] };
  37988. 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]] };
  37989. polyhedra[2] = {
  37990. 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]],
  37991. 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]]
  37992. };
  37993. polyhedra[3] = {
  37994. 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]],
  37995. 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]]
  37996. };
  37997. polyhedra[4] = {
  37998. 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]],
  37999. 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]]
  38000. };
  38001. 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]] };
  38002. 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]] };
  38003. 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]] };
  38004. 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]] };
  38005. 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]] };
  38006. 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]] };
  38007. 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]] };
  38008. 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]] };
  38009. 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]] };
  38010. polyhedra[14] = {
  38011. 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]],
  38012. 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]]
  38013. };
  38014. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38015. var size = options.size;
  38016. var sizeX = options.sizeX || size || 1;
  38017. var sizeY = options.sizeY || size || 1;
  38018. var sizeZ = options.sizeZ || size || 1;
  38019. var data = options.custom || polyhedra[type];
  38020. var nbfaces = data.face.length;
  38021. var faceUV = options.faceUV || new Array(nbfaces);
  38022. var faceColors = options.faceColors;
  38023. var flat = (options.flat === undefined) ? true : options.flat;
  38024. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38025. var positions = new Array();
  38026. var indices = new Array();
  38027. var normals = new Array();
  38028. var uvs = new Array();
  38029. var colors = new Array();
  38030. var index = 0;
  38031. var faceIdx = 0; // face cursor in the array "indexes"
  38032. var indexes = new Array();
  38033. var i = 0;
  38034. var f = 0;
  38035. var u, v, ang, x, y, tmp;
  38036. // default face colors and UV if undefined
  38037. if (flat) {
  38038. for (f = 0; f < nbfaces; f++) {
  38039. if (faceColors && faceColors[f] === undefined) {
  38040. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38041. }
  38042. if (faceUV && faceUV[f] === undefined) {
  38043. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38044. }
  38045. }
  38046. }
  38047. if (!flat) {
  38048. for (i = 0; i < data.vertex.length; i++) {
  38049. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38050. uvs.push(0, 0);
  38051. }
  38052. for (f = 0; f < nbfaces; f++) {
  38053. for (i = 0; i < data.face[f].length - 2; i++) {
  38054. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38055. }
  38056. }
  38057. }
  38058. else {
  38059. for (f = 0; f < nbfaces; f++) {
  38060. var fl = data.face[f].length; // number of vertices of the current face
  38061. ang = 2 * Math.PI / fl;
  38062. x = 0.5 * Math.tan(ang / 2);
  38063. y = 0.5;
  38064. // positions, uvs, colors
  38065. for (i = 0; i < fl; i++) {
  38066. // positions
  38067. 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);
  38068. indexes.push(index);
  38069. index++;
  38070. // uvs
  38071. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38072. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38073. uvs.push(u, v);
  38074. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38075. y = x * Math.sin(ang) + y * Math.cos(ang);
  38076. x = tmp;
  38077. // colors
  38078. if (faceColors) {
  38079. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38080. }
  38081. }
  38082. // indices from indexes
  38083. for (i = 0; i < fl - 2; i++) {
  38084. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38085. }
  38086. faceIdx += fl;
  38087. }
  38088. }
  38089. VertexData.ComputeNormals(positions, indices, normals);
  38090. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38091. var vertexData = new VertexData();
  38092. vertexData.positions = positions;
  38093. vertexData.indices = indices;
  38094. vertexData.normals = normals;
  38095. vertexData.uvs = uvs;
  38096. if (faceColors && flat) {
  38097. vertexData.colors = colors;
  38098. }
  38099. return vertexData;
  38100. };
  38101. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38102. /**
  38103. * Creates the VertexData for a TorusKnot
  38104. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38105. * * radius the radius of the torus knot, optional, default 2
  38106. * * tube the thickness of the tube, optional, default 0.5
  38107. * * radialSegments the number of sides on each tube segments, optional, default 32
  38108. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38109. * * p the number of windings around the z axis, optional, default 2
  38110. * * q the number of windings around the x axis, optional, default 3
  38111. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38112. * * 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)
  38113. * * 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)
  38114. * @returns the VertexData of the Torus Knot
  38115. */
  38116. VertexData.CreateTorusKnot = function (options) {
  38117. var indices = new Array();
  38118. var positions = new Array();
  38119. var normals = new Array();
  38120. var uvs = new Array();
  38121. var radius = options.radius || 2;
  38122. var tube = options.tube || 0.5;
  38123. var radialSegments = options.radialSegments || 32;
  38124. var tubularSegments = options.tubularSegments || 32;
  38125. var p = options.p || 2;
  38126. var q = options.q || 3;
  38127. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38128. // Helper
  38129. var getPos = function (angle) {
  38130. var cu = Math.cos(angle);
  38131. var su = Math.sin(angle);
  38132. var quOverP = q / p * angle;
  38133. var cs = Math.cos(quOverP);
  38134. var tx = radius * (2 + cs) * 0.5 * cu;
  38135. var ty = radius * (2 + cs) * su * 0.5;
  38136. var tz = radius * Math.sin(quOverP) * 0.5;
  38137. return new BABYLON.Vector3(tx, ty, tz);
  38138. };
  38139. // Vertices
  38140. var i;
  38141. var j;
  38142. for (i = 0; i <= radialSegments; i++) {
  38143. var modI = i % radialSegments;
  38144. var u = modI / radialSegments * 2 * p * Math.PI;
  38145. var p1 = getPos(u);
  38146. var p2 = getPos(u + 0.01);
  38147. var tang = p2.subtract(p1);
  38148. var n = p2.add(p1);
  38149. var bitan = BABYLON.Vector3.Cross(tang, n);
  38150. n = BABYLON.Vector3.Cross(bitan, tang);
  38151. bitan.normalize();
  38152. n.normalize();
  38153. for (j = 0; j < tubularSegments; j++) {
  38154. var modJ = j % tubularSegments;
  38155. var v = modJ / tubularSegments * 2 * Math.PI;
  38156. var cx = -tube * Math.cos(v);
  38157. var cy = tube * Math.sin(v);
  38158. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38159. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38160. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38161. uvs.push(i / radialSegments);
  38162. uvs.push(j / tubularSegments);
  38163. }
  38164. }
  38165. for (i = 0; i < radialSegments; i++) {
  38166. for (j = 0; j < tubularSegments; j++) {
  38167. var jNext = (j + 1) % tubularSegments;
  38168. var a = i * tubularSegments + j;
  38169. var b = (i + 1) * tubularSegments + j;
  38170. var c = (i + 1) * tubularSegments + jNext;
  38171. var d = i * tubularSegments + jNext;
  38172. indices.push(d);
  38173. indices.push(b);
  38174. indices.push(a);
  38175. indices.push(d);
  38176. indices.push(c);
  38177. indices.push(b);
  38178. }
  38179. }
  38180. // Normals
  38181. VertexData.ComputeNormals(positions, indices, normals);
  38182. // Sides
  38183. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38184. // Result
  38185. var vertexData = new VertexData();
  38186. vertexData.indices = indices;
  38187. vertexData.positions = positions;
  38188. vertexData.normals = normals;
  38189. vertexData.uvs = uvs;
  38190. return vertexData;
  38191. };
  38192. // Tools
  38193. /**
  38194. * Compute normals for given positions and indices
  38195. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38196. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38197. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38198. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38199. * * facetNormals : optional array of facet normals (vector3)
  38200. * * facetPositions : optional array of facet positions (vector3)
  38201. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38202. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38203. * * bInfo : optional bounding info, required for facetPartitioning computation
  38204. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38205. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38206. * * useRightHandedSystem: optional boolean to for right handed system computation
  38207. * * depthSort : optional boolean to enable the facet depth sort computation
  38208. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38209. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38210. */
  38211. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38212. // temporary scalar variables
  38213. var index = 0; // facet index
  38214. var p1p2x = 0.0; // p1p2 vector x coordinate
  38215. var p1p2y = 0.0; // p1p2 vector y coordinate
  38216. var p1p2z = 0.0; // p1p2 vector z coordinate
  38217. var p3p2x = 0.0; // p3p2 vector x coordinate
  38218. var p3p2y = 0.0; // p3p2 vector y coordinate
  38219. var p3p2z = 0.0; // p3p2 vector z coordinate
  38220. var faceNormalx = 0.0; // facet normal x coordinate
  38221. var faceNormaly = 0.0; // facet normal y coordinate
  38222. var faceNormalz = 0.0; // facet normal z coordinate
  38223. var length = 0.0; // facet normal length before normalization
  38224. var v1x = 0; // vector1 x index in the positions array
  38225. var v1y = 0; // vector1 y index in the positions array
  38226. var v1z = 0; // vector1 z index in the positions array
  38227. var v2x = 0; // vector2 x index in the positions array
  38228. var v2y = 0; // vector2 y index in the positions array
  38229. var v2z = 0; // vector2 z index in the positions array
  38230. var v3x = 0; // vector3 x index in the positions array
  38231. var v3y = 0; // vector3 y index in the positions array
  38232. var v3z = 0; // vector3 z index in the positions array
  38233. var computeFacetNormals = false;
  38234. var computeFacetPositions = false;
  38235. var computeFacetPartitioning = false;
  38236. var computeDepthSort = false;
  38237. var faceNormalSign = 1;
  38238. var ratio = 0;
  38239. var distanceTo = null;
  38240. if (options) {
  38241. computeFacetNormals = (options.facetNormals) ? true : false;
  38242. computeFacetPositions = (options.facetPositions) ? true : false;
  38243. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38244. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38245. ratio = options.ratio || 0;
  38246. computeDepthSort = (options.depthSort) ? true : false;
  38247. distanceTo = (options.distanceTo);
  38248. if (computeDepthSort) {
  38249. if (distanceTo === undefined) {
  38250. distanceTo = BABYLON.Vector3.Zero();
  38251. }
  38252. var depthSortedFacets = options.depthSortedFacets;
  38253. }
  38254. }
  38255. // facetPartitioning reinit if needed
  38256. var xSubRatio = 0;
  38257. var ySubRatio = 0;
  38258. var zSubRatio = 0;
  38259. var subSq = 0;
  38260. if (computeFacetPartitioning && options && options.bbSize) {
  38261. var ox = 0; // X partitioning index for facet position
  38262. var oy = 0; // Y partinioning index for facet position
  38263. var oz = 0; // Z partinioning index for facet position
  38264. var b1x = 0; // X partitioning index for facet v1 vertex
  38265. var b1y = 0; // Y partitioning index for facet v1 vertex
  38266. var b1z = 0; // z partitioning index for facet v1 vertex
  38267. var b2x = 0; // X partitioning index for facet v2 vertex
  38268. var b2y = 0; // Y partitioning index for facet v2 vertex
  38269. var b2z = 0; // Z partitioning index for facet v2 vertex
  38270. var b3x = 0; // X partitioning index for facet v3 vertex
  38271. var b3y = 0; // Y partitioning index for facet v3 vertex
  38272. var b3z = 0; // Z partitioning index for facet v3 vertex
  38273. var block_idx_o = 0; // facet barycenter block index
  38274. var block_idx_v1 = 0; // v1 vertex block index
  38275. var block_idx_v2 = 0; // v2 vertex block index
  38276. var block_idx_v3 = 0; // v3 vertex block index
  38277. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38278. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38279. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38280. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38281. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38282. subSq = options.subDiv.max * options.subDiv.max;
  38283. options.facetPartitioning.length = 0;
  38284. }
  38285. // reset the normals
  38286. for (index = 0; index < positions.length; index++) {
  38287. normals[index] = 0.0;
  38288. }
  38289. // Loop : 1 indice triplet = 1 facet
  38290. var nbFaces = (indices.length / 3) | 0;
  38291. for (index = 0; index < nbFaces; index++) {
  38292. // get the indexes of the coordinates of each vertex of the facet
  38293. v1x = indices[index * 3] * 3;
  38294. v1y = v1x + 1;
  38295. v1z = v1x + 2;
  38296. v2x = indices[index * 3 + 1] * 3;
  38297. v2y = v2x + 1;
  38298. v2z = v2x + 2;
  38299. v3x = indices[index * 3 + 2] * 3;
  38300. v3y = v3x + 1;
  38301. v3z = v3x + 2;
  38302. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38303. p1p2y = positions[v1y] - positions[v2y];
  38304. p1p2z = positions[v1z] - positions[v2z];
  38305. p3p2x = positions[v3x] - positions[v2x];
  38306. p3p2y = positions[v3y] - positions[v2y];
  38307. p3p2z = positions[v3z] - positions[v2z];
  38308. // compute the face normal with the cross product
  38309. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38310. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38311. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38312. // normalize this normal and store it in the array facetData
  38313. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38314. length = (length === 0) ? 1.0 : length;
  38315. faceNormalx /= length;
  38316. faceNormaly /= length;
  38317. faceNormalz /= length;
  38318. if (computeFacetNormals && options) {
  38319. options.facetNormals[index].x = faceNormalx;
  38320. options.facetNormals[index].y = faceNormaly;
  38321. options.facetNormals[index].z = faceNormalz;
  38322. }
  38323. if (computeFacetPositions && options) {
  38324. // compute and the facet barycenter coordinates in the array facetPositions
  38325. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38326. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38327. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38328. }
  38329. if (computeFacetPartitioning && options) {
  38330. // store the facet indexes in arrays in the main facetPartitioning array :
  38331. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38332. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38333. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38334. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38335. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38336. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38337. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38338. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38339. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38340. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38341. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38342. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38343. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38344. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38345. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38346. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38347. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38348. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38349. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38350. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38351. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38352. // push each facet index in each block containing the vertex
  38353. options.facetPartitioning[block_idx_v1].push(index);
  38354. if (block_idx_v2 != block_idx_v1) {
  38355. options.facetPartitioning[block_idx_v2].push(index);
  38356. }
  38357. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38358. options.facetPartitioning[block_idx_v3].push(index);
  38359. }
  38360. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38361. options.facetPartitioning[block_idx_o].push(index);
  38362. }
  38363. }
  38364. if (computeDepthSort && options && options.facetPositions) {
  38365. var dsf = depthSortedFacets[index];
  38366. dsf.ind = index * 3;
  38367. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38368. }
  38369. // compute the normals anyway
  38370. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38371. normals[v1y] += faceNormaly;
  38372. normals[v1z] += faceNormalz;
  38373. normals[v2x] += faceNormalx;
  38374. normals[v2y] += faceNormaly;
  38375. normals[v2z] += faceNormalz;
  38376. normals[v3x] += faceNormalx;
  38377. normals[v3y] += faceNormaly;
  38378. normals[v3z] += faceNormalz;
  38379. }
  38380. // last normalization of each normal
  38381. for (index = 0; index < normals.length / 3; index++) {
  38382. faceNormalx = normals[index * 3];
  38383. faceNormaly = normals[index * 3 + 1];
  38384. faceNormalz = normals[index * 3 + 2];
  38385. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38386. length = (length === 0) ? 1.0 : length;
  38387. faceNormalx /= length;
  38388. faceNormaly /= length;
  38389. faceNormalz /= length;
  38390. normals[index * 3] = faceNormalx;
  38391. normals[index * 3 + 1] = faceNormaly;
  38392. normals[index * 3 + 2] = faceNormalz;
  38393. }
  38394. };
  38395. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38396. var li = indices.length;
  38397. var ln = normals.length;
  38398. var i;
  38399. var n;
  38400. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38401. switch (sideOrientation) {
  38402. case BABYLON.Mesh.FRONTSIDE:
  38403. // nothing changed
  38404. break;
  38405. case BABYLON.Mesh.BACKSIDE:
  38406. var tmp;
  38407. // indices
  38408. for (i = 0; i < li; i += 3) {
  38409. tmp = indices[i];
  38410. indices[i] = indices[i + 2];
  38411. indices[i + 2] = tmp;
  38412. }
  38413. // normals
  38414. for (n = 0; n < ln; n++) {
  38415. normals[n] = -normals[n];
  38416. }
  38417. break;
  38418. case BABYLON.Mesh.DOUBLESIDE:
  38419. // positions
  38420. var lp = positions.length;
  38421. var l = lp / 3;
  38422. for (var p = 0; p < lp; p++) {
  38423. positions[lp + p] = positions[p];
  38424. }
  38425. // indices
  38426. for (i = 0; i < li; i += 3) {
  38427. indices[i + li] = indices[i + 2] + l;
  38428. indices[i + 1 + li] = indices[i + 1] + l;
  38429. indices[i + 2 + li] = indices[i] + l;
  38430. }
  38431. // normals
  38432. for (n = 0; n < ln; n++) {
  38433. normals[ln + n] = -normals[n];
  38434. }
  38435. // uvs
  38436. var lu = uvs.length;
  38437. var u = 0;
  38438. for (u = 0; u < lu; u++) {
  38439. uvs[u + lu] = uvs[u];
  38440. }
  38441. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38442. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38443. u = 0;
  38444. for (i = 0; i < lu / 2; i++) {
  38445. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38446. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38447. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38448. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38449. u += 2;
  38450. }
  38451. break;
  38452. }
  38453. };
  38454. /**
  38455. * Applies VertexData created from the imported parameters to the geometry
  38456. * @param parsedVertexData the parsed data from an imported file
  38457. * @param geometry the geometry to apply the VertexData to
  38458. */
  38459. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38460. var vertexData = new VertexData();
  38461. // positions
  38462. var positions = parsedVertexData.positions;
  38463. if (positions) {
  38464. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38465. }
  38466. // normals
  38467. var normals = parsedVertexData.normals;
  38468. if (normals) {
  38469. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38470. }
  38471. // tangents
  38472. var tangents = parsedVertexData.tangents;
  38473. if (tangents) {
  38474. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38475. }
  38476. // uvs
  38477. var uvs = parsedVertexData.uvs;
  38478. if (uvs) {
  38479. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38480. }
  38481. // uv2s
  38482. var uv2s = parsedVertexData.uv2s;
  38483. if (uv2s) {
  38484. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38485. }
  38486. // uv3s
  38487. var uv3s = parsedVertexData.uv3s;
  38488. if (uv3s) {
  38489. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38490. }
  38491. // uv4s
  38492. var uv4s = parsedVertexData.uv4s;
  38493. if (uv4s) {
  38494. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38495. }
  38496. // uv5s
  38497. var uv5s = parsedVertexData.uv5s;
  38498. if (uv5s) {
  38499. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38500. }
  38501. // uv6s
  38502. var uv6s = parsedVertexData.uv6s;
  38503. if (uv6s) {
  38504. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38505. }
  38506. // colors
  38507. var colors = parsedVertexData.colors;
  38508. if (colors) {
  38509. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38510. }
  38511. // matricesIndices
  38512. var matricesIndices = parsedVertexData.matricesIndices;
  38513. if (matricesIndices) {
  38514. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38515. }
  38516. // matricesWeights
  38517. var matricesWeights = parsedVertexData.matricesWeights;
  38518. if (matricesWeights) {
  38519. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38520. }
  38521. // indices
  38522. var indices = parsedVertexData.indices;
  38523. if (indices) {
  38524. vertexData.indices = indices;
  38525. }
  38526. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38527. };
  38528. return VertexData;
  38529. }());
  38530. BABYLON.VertexData = VertexData;
  38531. })(BABYLON || (BABYLON = {}));
  38532. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38533. var BABYLON;
  38534. (function (BABYLON) {
  38535. /**
  38536. * Class used to store geometry data (vertex buffers + index buffer)
  38537. */
  38538. var Geometry = /** @class */ (function () {
  38539. /**
  38540. * Creates a new geometry
  38541. * @param id defines the unique ID
  38542. * @param scene defines the hosting scene
  38543. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38544. * @param updatable defines if geometry must be updatable (false by default)
  38545. * @param mesh defines the mesh that will be associated with the geometry
  38546. */
  38547. function Geometry(id, scene, vertexData, updatable, mesh) {
  38548. if (updatable === void 0) { updatable = false; }
  38549. if (mesh === void 0) { mesh = null; }
  38550. /**
  38551. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38552. */
  38553. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38554. this._totalVertices = 0;
  38555. this._isDisposed = false;
  38556. this._indexBufferIsUpdatable = false;
  38557. this.id = id;
  38558. this._engine = scene.getEngine();
  38559. this._meshes = [];
  38560. this._scene = scene;
  38561. //Init vertex buffer cache
  38562. this._vertexBuffers = {};
  38563. this._indices = [];
  38564. this._updatable = updatable;
  38565. // vertexData
  38566. if (vertexData) {
  38567. this.setAllVerticesData(vertexData, updatable);
  38568. }
  38569. else {
  38570. this._totalVertices = 0;
  38571. this._indices = [];
  38572. }
  38573. if (this._engine.getCaps().vertexArrayObject) {
  38574. this._vertexArrayObjects = {};
  38575. }
  38576. // applyToMesh
  38577. if (mesh) {
  38578. if (mesh.getClassName() === "LinesMesh") {
  38579. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38580. this._updateExtend();
  38581. }
  38582. this.applyToMesh(mesh);
  38583. mesh.computeWorldMatrix(true);
  38584. }
  38585. }
  38586. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38587. /**
  38588. * 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
  38589. */
  38590. get: function () {
  38591. return this._boundingBias;
  38592. },
  38593. /**
  38594. * 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
  38595. */
  38596. set: function (value) {
  38597. if (this._boundingBias && this._boundingBias.equals(value)) {
  38598. return;
  38599. }
  38600. this._boundingBias = value.clone();
  38601. this._updateBoundingInfo(true, null);
  38602. },
  38603. enumerable: true,
  38604. configurable: true
  38605. });
  38606. /**
  38607. * Static function used to attach a new empty geometry to a mesh
  38608. * @param mesh defines the mesh to attach the geometry to
  38609. * @returns the new {BABYLON.Geometry}
  38610. */
  38611. Geometry.CreateGeometryForMesh = function (mesh) {
  38612. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38613. geometry.applyToMesh(mesh);
  38614. return geometry;
  38615. };
  38616. Object.defineProperty(Geometry.prototype, "extend", {
  38617. /**
  38618. * Gets the current extend of the geometry
  38619. */
  38620. get: function () {
  38621. return this._extend;
  38622. },
  38623. enumerable: true,
  38624. configurable: true
  38625. });
  38626. /**
  38627. * Gets the hosting scene
  38628. * @returns the hosting {BABYLON.Scene}
  38629. */
  38630. Geometry.prototype.getScene = function () {
  38631. return this._scene;
  38632. };
  38633. /**
  38634. * Gets the hosting engine
  38635. * @returns the hosting {BABYLON.Engine}
  38636. */
  38637. Geometry.prototype.getEngine = function () {
  38638. return this._engine;
  38639. };
  38640. /**
  38641. * Defines if the geometry is ready to use
  38642. * @returns true if the geometry is ready to be used
  38643. */
  38644. Geometry.prototype.isReady = function () {
  38645. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38646. };
  38647. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38648. /**
  38649. * Gets a value indicating that the geometry should not be serialized
  38650. */
  38651. get: function () {
  38652. for (var index = 0; index < this._meshes.length; index++) {
  38653. if (!this._meshes[index].doNotSerialize) {
  38654. return false;
  38655. }
  38656. }
  38657. return true;
  38658. },
  38659. enumerable: true,
  38660. configurable: true
  38661. });
  38662. /** @hidden */
  38663. Geometry.prototype._rebuild = function () {
  38664. if (this._vertexArrayObjects) {
  38665. this._vertexArrayObjects = {};
  38666. }
  38667. // Index buffer
  38668. if (this._meshes.length !== 0 && this._indices) {
  38669. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38670. }
  38671. // Vertex buffers
  38672. for (var key in this._vertexBuffers) {
  38673. var vertexBuffer = this._vertexBuffers[key];
  38674. vertexBuffer._rebuild();
  38675. }
  38676. };
  38677. /**
  38678. * Affects all gemetry data in one call
  38679. * @param vertexData defines the geometry data
  38680. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38681. */
  38682. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38683. vertexData.applyToGeometry(this, updatable);
  38684. this.notifyUpdate();
  38685. };
  38686. /**
  38687. * Set specific vertex data
  38688. * @param kind defines the data kind (Position, normal, etc...)
  38689. * @param data defines the vertex data to use
  38690. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38691. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38692. */
  38693. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38694. if (updatable === void 0) { updatable = false; }
  38695. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38696. this.setVerticesBuffer(buffer);
  38697. };
  38698. /**
  38699. * Removes a specific vertex data
  38700. * @param kind defines the data kind (Position, normal, etc...)
  38701. */
  38702. Geometry.prototype.removeVerticesData = function (kind) {
  38703. if (this._vertexBuffers[kind]) {
  38704. this._vertexBuffers[kind].dispose();
  38705. delete this._vertexBuffers[kind];
  38706. }
  38707. };
  38708. /**
  38709. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38710. * @param buffer defines the vertex buffer to use
  38711. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38712. */
  38713. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38714. if (totalVertices === void 0) { totalVertices = null; }
  38715. var kind = buffer.getKind();
  38716. if (this._vertexBuffers[kind]) {
  38717. this._vertexBuffers[kind].dispose();
  38718. }
  38719. this._vertexBuffers[kind] = buffer;
  38720. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38721. var data = buffer.getData();
  38722. if (totalVertices != null) {
  38723. this._totalVertices = totalVertices;
  38724. }
  38725. else {
  38726. if (data != null) {
  38727. this._totalVertices = data.length / (buffer.byteStride / 4);
  38728. }
  38729. }
  38730. this._updateExtend(data);
  38731. this._resetPointsArrayCache();
  38732. var meshes = this._meshes;
  38733. var numOfMeshes = meshes.length;
  38734. for (var index = 0; index < numOfMeshes; index++) {
  38735. var mesh = meshes[index];
  38736. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38737. mesh._createGlobalSubMesh(false);
  38738. mesh.computeWorldMatrix(true);
  38739. }
  38740. }
  38741. this.notifyUpdate(kind);
  38742. if (this._vertexArrayObjects) {
  38743. this._disposeVertexArrayObjects();
  38744. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38745. }
  38746. };
  38747. /**
  38748. * Update a specific vertex buffer
  38749. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38750. * It will do nothing if the buffer is not updatable
  38751. * @param kind defines the data kind (Position, normal, etc...)
  38752. * @param data defines the data to use
  38753. * @param offset defines the offset in the target buffer where to store the data
  38754. * @param useBytes set to true if the offset is in bytes
  38755. */
  38756. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38757. if (useBytes === void 0) { useBytes = false; }
  38758. var vertexBuffer = this.getVertexBuffer(kind);
  38759. if (!vertexBuffer) {
  38760. return;
  38761. }
  38762. vertexBuffer.updateDirectly(data, offset, useBytes);
  38763. this.notifyUpdate(kind);
  38764. };
  38765. /**
  38766. * Update a specific vertex buffer
  38767. * This function will create a new buffer if the current one is not updatable
  38768. * @param kind defines the data kind (Position, normal, etc...)
  38769. * @param data defines the data to use
  38770. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38771. */
  38772. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38773. if (updateExtends === void 0) { updateExtends = false; }
  38774. var vertexBuffer = this.getVertexBuffer(kind);
  38775. if (!vertexBuffer) {
  38776. return;
  38777. }
  38778. vertexBuffer.update(data);
  38779. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38780. this._updateBoundingInfo(updateExtends, data);
  38781. }
  38782. this.notifyUpdate(kind);
  38783. };
  38784. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38785. if (updateExtends) {
  38786. this._updateExtend(data);
  38787. }
  38788. var meshes = this._meshes;
  38789. var numOfMeshes = meshes.length;
  38790. this._resetPointsArrayCache();
  38791. for (var index = 0; index < numOfMeshes; index++) {
  38792. var mesh = meshes[index];
  38793. if (updateExtends) {
  38794. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38795. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38796. var subMesh = mesh.subMeshes[subIndex];
  38797. subMesh.refreshBoundingInfo();
  38798. }
  38799. }
  38800. }
  38801. };
  38802. /** @hidden */
  38803. Geometry.prototype._bind = function (effect, indexToBind) {
  38804. if (!effect) {
  38805. return;
  38806. }
  38807. if (indexToBind === undefined) {
  38808. indexToBind = this._indexBuffer;
  38809. }
  38810. var vbs = this.getVertexBuffers();
  38811. if (!vbs) {
  38812. return;
  38813. }
  38814. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38815. this._engine.bindBuffers(vbs, indexToBind, effect);
  38816. return;
  38817. }
  38818. // Using VAO
  38819. if (!this._vertexArrayObjects[effect.key]) {
  38820. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38821. }
  38822. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38823. };
  38824. /**
  38825. * Gets total number of vertices
  38826. * @returns the total number of vertices
  38827. */
  38828. Geometry.prototype.getTotalVertices = function () {
  38829. if (!this.isReady()) {
  38830. return 0;
  38831. }
  38832. return this._totalVertices;
  38833. };
  38834. /**
  38835. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38836. * @param kind defines the data kind (Position, normal, etc...)
  38837. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38838. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38839. * @returns a float array containing vertex data
  38840. */
  38841. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38842. var vertexBuffer = this.getVertexBuffer(kind);
  38843. if (!vertexBuffer) {
  38844. return null;
  38845. }
  38846. var data = vertexBuffer.getData();
  38847. if (!data) {
  38848. return null;
  38849. }
  38850. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38851. var count = this._totalVertices * vertexBuffer.getSize();
  38852. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38853. var copy_1 = new Array(count);
  38854. vertexBuffer.forEach(count, function (value, index) {
  38855. copy_1[index] = value;
  38856. });
  38857. return copy_1;
  38858. }
  38859. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38860. if (data instanceof Array) {
  38861. var offset = vertexBuffer.byteOffset / 4;
  38862. return BABYLON.Tools.Slice(data, offset, offset + count);
  38863. }
  38864. else if (data instanceof ArrayBuffer) {
  38865. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38866. }
  38867. else {
  38868. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38869. }
  38870. }
  38871. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38872. return BABYLON.Tools.Slice(data);
  38873. }
  38874. return data;
  38875. };
  38876. /**
  38877. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38878. * @param kind defines the data kind (Position, normal, etc...)
  38879. * @returns true if the vertex buffer with the specified kind is updatable
  38880. */
  38881. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38882. var vb = this._vertexBuffers[kind];
  38883. if (!vb) {
  38884. return false;
  38885. }
  38886. return vb.isUpdatable();
  38887. };
  38888. /**
  38889. * Gets a specific vertex buffer
  38890. * @param kind defines the data kind (Position, normal, etc...)
  38891. * @returns a {BABYLON.VertexBuffer}
  38892. */
  38893. Geometry.prototype.getVertexBuffer = function (kind) {
  38894. if (!this.isReady()) {
  38895. return null;
  38896. }
  38897. return this._vertexBuffers[kind];
  38898. };
  38899. /**
  38900. * Returns all vertex buffers
  38901. * @return an object holding all vertex buffers indexed by kind
  38902. */
  38903. Geometry.prototype.getVertexBuffers = function () {
  38904. if (!this.isReady()) {
  38905. return null;
  38906. }
  38907. return this._vertexBuffers;
  38908. };
  38909. /**
  38910. * Gets a boolean indicating if specific vertex buffer is present
  38911. * @param kind defines the data kind (Position, normal, etc...)
  38912. * @returns true if data is present
  38913. */
  38914. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38915. if (!this._vertexBuffers) {
  38916. if (this._delayInfo) {
  38917. return this._delayInfo.indexOf(kind) !== -1;
  38918. }
  38919. return false;
  38920. }
  38921. return this._vertexBuffers[kind] !== undefined;
  38922. };
  38923. /**
  38924. * Gets a list of all attached data kinds (Position, normal, etc...)
  38925. * @returns a list of string containing all kinds
  38926. */
  38927. Geometry.prototype.getVerticesDataKinds = function () {
  38928. var result = [];
  38929. var kind;
  38930. if (!this._vertexBuffers && this._delayInfo) {
  38931. for (kind in this._delayInfo) {
  38932. result.push(kind);
  38933. }
  38934. }
  38935. else {
  38936. for (kind in this._vertexBuffers) {
  38937. result.push(kind);
  38938. }
  38939. }
  38940. return result;
  38941. };
  38942. /**
  38943. * Update index buffer
  38944. * @param indices defines the indices to store in the index buffer
  38945. * @param offset defines the offset in the target buffer where to store the data
  38946. */
  38947. Geometry.prototype.updateIndices = function (indices, offset) {
  38948. if (!this._indexBuffer) {
  38949. return;
  38950. }
  38951. if (!this._indexBufferIsUpdatable) {
  38952. this.setIndices(indices, null, true);
  38953. }
  38954. else {
  38955. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38956. }
  38957. };
  38958. /**
  38959. * Creates a new index buffer
  38960. * @param indices defines the indices to store in the index buffer
  38961. * @param totalVertices defines the total number of vertices (could be null)
  38962. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38963. */
  38964. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38965. if (totalVertices === void 0) { totalVertices = null; }
  38966. if (updatable === void 0) { updatable = false; }
  38967. if (this._indexBuffer) {
  38968. this._engine._releaseBuffer(this._indexBuffer);
  38969. }
  38970. this._disposeVertexArrayObjects();
  38971. this._indices = indices;
  38972. this._indexBufferIsUpdatable = updatable;
  38973. if (this._meshes.length !== 0 && this._indices) {
  38974. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38975. }
  38976. if (totalVertices != undefined) { // including null and undefined
  38977. this._totalVertices = totalVertices;
  38978. }
  38979. var meshes = this._meshes;
  38980. var numOfMeshes = meshes.length;
  38981. for (var index = 0; index < numOfMeshes; index++) {
  38982. meshes[index]._createGlobalSubMesh(true);
  38983. }
  38984. this.notifyUpdate();
  38985. };
  38986. /**
  38987. * Return the total number of indices
  38988. * @returns the total number of indices
  38989. */
  38990. Geometry.prototype.getTotalIndices = function () {
  38991. if (!this.isReady()) {
  38992. return 0;
  38993. }
  38994. return this._indices.length;
  38995. };
  38996. /**
  38997. * Gets the index buffer array
  38998. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38999. * @returns the index buffer array
  39000. */
  39001. Geometry.prototype.getIndices = function (copyWhenShared) {
  39002. if (!this.isReady()) {
  39003. return null;
  39004. }
  39005. var orig = this._indices;
  39006. if (!copyWhenShared || this._meshes.length === 1) {
  39007. return orig;
  39008. }
  39009. else {
  39010. var len = orig.length;
  39011. var copy = [];
  39012. for (var i = 0; i < len; i++) {
  39013. copy.push(orig[i]);
  39014. }
  39015. return copy;
  39016. }
  39017. };
  39018. /**
  39019. * Gets the index buffer
  39020. * @return the index buffer
  39021. */
  39022. Geometry.prototype.getIndexBuffer = function () {
  39023. if (!this.isReady()) {
  39024. return null;
  39025. }
  39026. return this._indexBuffer;
  39027. };
  39028. /** @hidden */
  39029. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39030. if (effect === void 0) { effect = null; }
  39031. if (!effect || !this._vertexArrayObjects) {
  39032. return;
  39033. }
  39034. if (this._vertexArrayObjects[effect.key]) {
  39035. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39036. delete this._vertexArrayObjects[effect.key];
  39037. }
  39038. };
  39039. /**
  39040. * Release the associated resources for a specific mesh
  39041. * @param mesh defines the source mesh
  39042. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39043. */
  39044. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39045. var meshes = this._meshes;
  39046. var index = meshes.indexOf(mesh);
  39047. if (index === -1) {
  39048. return;
  39049. }
  39050. meshes.splice(index, 1);
  39051. mesh._geometry = null;
  39052. if (meshes.length === 0 && shouldDispose) {
  39053. this.dispose();
  39054. }
  39055. };
  39056. /**
  39057. * Apply current geometry to a given mesh
  39058. * @param mesh defines the mesh to apply geometry to
  39059. */
  39060. Geometry.prototype.applyToMesh = function (mesh) {
  39061. if (mesh._geometry === this) {
  39062. return;
  39063. }
  39064. var previousGeometry = mesh._geometry;
  39065. if (previousGeometry) {
  39066. previousGeometry.releaseForMesh(mesh);
  39067. }
  39068. var meshes = this._meshes;
  39069. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39070. mesh._geometry = this;
  39071. this._scene.pushGeometry(this);
  39072. meshes.push(mesh);
  39073. if (this.isReady()) {
  39074. this._applyToMesh(mesh);
  39075. }
  39076. else {
  39077. mesh._boundingInfo = this._boundingInfo;
  39078. }
  39079. };
  39080. Geometry.prototype._updateExtend = function (data) {
  39081. if (data === void 0) { data = null; }
  39082. if (!data) {
  39083. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39084. }
  39085. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39086. };
  39087. Geometry.prototype._applyToMesh = function (mesh) {
  39088. var numOfMeshes = this._meshes.length;
  39089. // vertexBuffers
  39090. for (var kind in this._vertexBuffers) {
  39091. if (numOfMeshes === 1) {
  39092. this._vertexBuffers[kind].create();
  39093. }
  39094. var buffer = this._vertexBuffers[kind].getBuffer();
  39095. if (buffer)
  39096. buffer.references = numOfMeshes;
  39097. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39098. if (!this._extend) {
  39099. this._updateExtend();
  39100. }
  39101. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39102. mesh._createGlobalSubMesh(false);
  39103. //bounding info was just created again, world matrix should be applied again.
  39104. mesh._updateBoundingInfo();
  39105. }
  39106. }
  39107. // indexBuffer
  39108. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39109. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39110. }
  39111. if (this._indexBuffer) {
  39112. this._indexBuffer.references = numOfMeshes;
  39113. }
  39114. };
  39115. Geometry.prototype.notifyUpdate = function (kind) {
  39116. if (this.onGeometryUpdated) {
  39117. this.onGeometryUpdated(this, kind);
  39118. }
  39119. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39120. var mesh = _a[_i];
  39121. mesh._markSubMeshesAsAttributesDirty();
  39122. }
  39123. };
  39124. /**
  39125. * Load the geometry if it was flagged as delay loaded
  39126. * @param scene defines the hosting scene
  39127. * @param onLoaded defines a callback called when the geometry is loaded
  39128. */
  39129. Geometry.prototype.load = function (scene, onLoaded) {
  39130. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39131. return;
  39132. }
  39133. if (this.isReady()) {
  39134. if (onLoaded) {
  39135. onLoaded();
  39136. }
  39137. return;
  39138. }
  39139. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39140. this._queueLoad(scene, onLoaded);
  39141. };
  39142. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39143. var _this = this;
  39144. if (!this.delayLoadingFile) {
  39145. return;
  39146. }
  39147. scene._addPendingData(this);
  39148. scene._loadFile(this.delayLoadingFile, function (data) {
  39149. if (!_this._delayLoadingFunction) {
  39150. return;
  39151. }
  39152. _this._delayLoadingFunction(JSON.parse(data), _this);
  39153. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39154. _this._delayInfo = [];
  39155. scene._removePendingData(_this);
  39156. var meshes = _this._meshes;
  39157. var numOfMeshes = meshes.length;
  39158. for (var index = 0; index < numOfMeshes; index++) {
  39159. _this._applyToMesh(meshes[index]);
  39160. }
  39161. if (onLoaded) {
  39162. onLoaded();
  39163. }
  39164. }, undefined, true);
  39165. };
  39166. /**
  39167. * Invert the geometry to move from a right handed system to a left handed one.
  39168. */
  39169. Geometry.prototype.toLeftHanded = function () {
  39170. // Flip faces
  39171. var tIndices = this.getIndices(false);
  39172. if (tIndices != null && tIndices.length > 0) {
  39173. for (var i = 0; i < tIndices.length; i += 3) {
  39174. var tTemp = tIndices[i + 0];
  39175. tIndices[i + 0] = tIndices[i + 2];
  39176. tIndices[i + 2] = tTemp;
  39177. }
  39178. this.setIndices(tIndices);
  39179. }
  39180. // Negate position.z
  39181. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39182. if (tPositions != null && tPositions.length > 0) {
  39183. for (var i = 0; i < tPositions.length; i += 3) {
  39184. tPositions[i + 2] = -tPositions[i + 2];
  39185. }
  39186. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39187. }
  39188. // Negate normal.z
  39189. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39190. if (tNormals != null && tNormals.length > 0) {
  39191. for (var i = 0; i < tNormals.length; i += 3) {
  39192. tNormals[i + 2] = -tNormals[i + 2];
  39193. }
  39194. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39195. }
  39196. };
  39197. // Cache
  39198. /** @hidden */
  39199. Geometry.prototype._resetPointsArrayCache = function () {
  39200. this._positions = null;
  39201. };
  39202. /** @hidden */
  39203. Geometry.prototype._generatePointsArray = function () {
  39204. if (this._positions)
  39205. return true;
  39206. this._positions = [];
  39207. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39208. if (!data) {
  39209. return false;
  39210. }
  39211. for (var index = 0; index < data.length; index += 3) {
  39212. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39213. }
  39214. return true;
  39215. };
  39216. /**
  39217. * Gets a value indicating if the geometry is disposed
  39218. * @returns true if the geometry was disposed
  39219. */
  39220. Geometry.prototype.isDisposed = function () {
  39221. return this._isDisposed;
  39222. };
  39223. Geometry.prototype._disposeVertexArrayObjects = function () {
  39224. if (this._vertexArrayObjects) {
  39225. for (var kind in this._vertexArrayObjects) {
  39226. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39227. }
  39228. this._vertexArrayObjects = {};
  39229. }
  39230. };
  39231. /**
  39232. * Free all associated resources
  39233. */
  39234. Geometry.prototype.dispose = function () {
  39235. var meshes = this._meshes;
  39236. var numOfMeshes = meshes.length;
  39237. var index;
  39238. for (index = 0; index < numOfMeshes; index++) {
  39239. this.releaseForMesh(meshes[index]);
  39240. }
  39241. this._meshes = [];
  39242. this._disposeVertexArrayObjects();
  39243. for (var kind in this._vertexBuffers) {
  39244. this._vertexBuffers[kind].dispose();
  39245. }
  39246. this._vertexBuffers = {};
  39247. this._totalVertices = 0;
  39248. if (this._indexBuffer) {
  39249. this._engine._releaseBuffer(this._indexBuffer);
  39250. }
  39251. this._indexBuffer = null;
  39252. this._indices = [];
  39253. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39254. this.delayLoadingFile = null;
  39255. this._delayLoadingFunction = null;
  39256. this._delayInfo = [];
  39257. this._boundingInfo = null;
  39258. this._scene.removeGeometry(this);
  39259. this._isDisposed = true;
  39260. };
  39261. /**
  39262. * Clone the current geometry into a new geometry
  39263. * @param id defines the unique ID of the new geometry
  39264. * @returns a new geometry object
  39265. */
  39266. Geometry.prototype.copy = function (id) {
  39267. var vertexData = new BABYLON.VertexData();
  39268. vertexData.indices = [];
  39269. var indices = this.getIndices();
  39270. if (indices) {
  39271. for (var index = 0; index < indices.length; index++) {
  39272. vertexData.indices.push(indices[index]);
  39273. }
  39274. }
  39275. var updatable = false;
  39276. var stopChecking = false;
  39277. var kind;
  39278. for (kind in this._vertexBuffers) {
  39279. // using slice() to make a copy of the array and not just reference it
  39280. var data = this.getVerticesData(kind);
  39281. if (data instanceof Float32Array) {
  39282. vertexData.set(new Float32Array(data), kind);
  39283. }
  39284. else {
  39285. vertexData.set(data.slice(0), kind);
  39286. }
  39287. if (!stopChecking) {
  39288. var vb = this.getVertexBuffer(kind);
  39289. if (vb) {
  39290. updatable = vb.isUpdatable();
  39291. stopChecking = !updatable;
  39292. }
  39293. }
  39294. }
  39295. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39296. geometry.delayLoadState = this.delayLoadState;
  39297. geometry.delayLoadingFile = this.delayLoadingFile;
  39298. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39299. for (kind in this._delayInfo) {
  39300. geometry._delayInfo = geometry._delayInfo || [];
  39301. geometry._delayInfo.push(kind);
  39302. }
  39303. // Bounding info
  39304. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39305. return geometry;
  39306. };
  39307. /**
  39308. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39309. * @return a JSON representation of the current geometry data (without the vertices data)
  39310. */
  39311. Geometry.prototype.serialize = function () {
  39312. var serializationObject = {};
  39313. serializationObject.id = this.id;
  39314. serializationObject.updatable = this._updatable;
  39315. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39316. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39317. }
  39318. return serializationObject;
  39319. };
  39320. Geometry.prototype.toNumberArray = function (origin) {
  39321. if (Array.isArray(origin)) {
  39322. return origin;
  39323. }
  39324. else {
  39325. return Array.prototype.slice.call(origin);
  39326. }
  39327. };
  39328. /**
  39329. * Serialize all vertices data into a JSON oject
  39330. * @returns a JSON representation of the current geometry data
  39331. */
  39332. Geometry.prototype.serializeVerticeData = function () {
  39333. var serializationObject = this.serialize();
  39334. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39335. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39336. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39337. serializationObject.positions._updatable = true;
  39338. }
  39339. }
  39340. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39341. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39342. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39343. serializationObject.normals._updatable = true;
  39344. }
  39345. }
  39346. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39347. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39348. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39349. serializationObject.tangets._updatable = true;
  39350. }
  39351. }
  39352. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39353. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39354. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39355. serializationObject.uvs._updatable = true;
  39356. }
  39357. }
  39358. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39359. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39360. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39361. serializationObject.uv2s._updatable = true;
  39362. }
  39363. }
  39364. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39365. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39366. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39367. serializationObject.uv3s._updatable = true;
  39368. }
  39369. }
  39370. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39371. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39372. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39373. serializationObject.uv4s._updatable = true;
  39374. }
  39375. }
  39376. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39377. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39378. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39379. serializationObject.uv5s._updatable = true;
  39380. }
  39381. }
  39382. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39383. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39384. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39385. serializationObject.uv6s._updatable = true;
  39386. }
  39387. }
  39388. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39389. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39390. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39391. serializationObject.colors._updatable = true;
  39392. }
  39393. }
  39394. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39395. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39396. serializationObject.matricesIndices._isExpanded = true;
  39397. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39398. serializationObject.matricesIndices._updatable = true;
  39399. }
  39400. }
  39401. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39402. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39403. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39404. serializationObject.matricesWeights._updatable = true;
  39405. }
  39406. }
  39407. serializationObject.indices = this.toNumberArray(this.getIndices());
  39408. return serializationObject;
  39409. };
  39410. // Statics
  39411. /**
  39412. * Extracts a clone of a mesh geometry
  39413. * @param mesh defines the source mesh
  39414. * @param id defines the unique ID of the new geometry object
  39415. * @returns the new geometry object
  39416. */
  39417. Geometry.ExtractFromMesh = function (mesh, id) {
  39418. var geometry = mesh._geometry;
  39419. if (!geometry) {
  39420. return null;
  39421. }
  39422. return geometry.copy(id);
  39423. };
  39424. /**
  39425. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39426. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39427. * Be aware Math.random() could cause collisions, but:
  39428. * "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"
  39429. * @returns a string containing a new GUID
  39430. */
  39431. Geometry.RandomId = function () {
  39432. return BABYLON.Tools.RandomId();
  39433. };
  39434. /** @hidden */
  39435. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39436. var scene = mesh.getScene();
  39437. // Geometry
  39438. var geometryId = parsedGeometry.geometryId;
  39439. if (geometryId) {
  39440. var geometry = scene.getGeometryByID(geometryId);
  39441. if (geometry) {
  39442. geometry.applyToMesh(mesh);
  39443. }
  39444. }
  39445. else if (parsedGeometry instanceof ArrayBuffer) {
  39446. var binaryInfo = mesh._binaryInfo;
  39447. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39448. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39449. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39450. }
  39451. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39452. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39453. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39454. }
  39455. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39456. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39457. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39458. }
  39459. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39460. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39461. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39462. }
  39463. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39464. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39465. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39466. }
  39467. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39468. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39469. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39470. }
  39471. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39472. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39473. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39474. }
  39475. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39476. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39477. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39478. }
  39479. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39480. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39481. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39482. }
  39483. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39484. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39485. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39486. }
  39487. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39488. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39489. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39490. }
  39491. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39492. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39493. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39494. }
  39495. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39496. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39497. mesh.setIndices(indicesData, null);
  39498. }
  39499. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39500. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39501. mesh.subMeshes = [];
  39502. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39503. var materialIndex = subMeshesData[(i * 5) + 0];
  39504. var verticesStart = subMeshesData[(i * 5) + 1];
  39505. var verticesCount = subMeshesData[(i * 5) + 2];
  39506. var indexStart = subMeshesData[(i * 5) + 3];
  39507. var indexCount = subMeshesData[(i * 5) + 4];
  39508. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39509. }
  39510. }
  39511. }
  39512. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39513. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39514. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39515. if (parsedGeometry.tangents) {
  39516. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39517. }
  39518. if (parsedGeometry.uvs) {
  39519. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39520. }
  39521. if (parsedGeometry.uvs2) {
  39522. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39523. }
  39524. if (parsedGeometry.uvs3) {
  39525. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39526. }
  39527. if (parsedGeometry.uvs4) {
  39528. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39529. }
  39530. if (parsedGeometry.uvs5) {
  39531. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39532. }
  39533. if (parsedGeometry.uvs6) {
  39534. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39535. }
  39536. if (parsedGeometry.colors) {
  39537. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39538. }
  39539. if (parsedGeometry.matricesIndices) {
  39540. if (!parsedGeometry.matricesIndices._isExpanded) {
  39541. var floatIndices = [];
  39542. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39543. var matricesIndex = parsedGeometry.matricesIndices[i];
  39544. floatIndices.push(matricesIndex & 0x000000FF);
  39545. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39546. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39547. floatIndices.push(matricesIndex >> 24);
  39548. }
  39549. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39550. }
  39551. else {
  39552. delete parsedGeometry.matricesIndices._isExpanded;
  39553. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39554. }
  39555. }
  39556. if (parsedGeometry.matricesIndicesExtra) {
  39557. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39558. var floatIndices = [];
  39559. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39560. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39561. floatIndices.push(matricesIndex & 0x000000FF);
  39562. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39563. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39564. floatIndices.push(matricesIndex >> 24);
  39565. }
  39566. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39567. }
  39568. else {
  39569. delete parsedGeometry.matricesIndices._isExpanded;
  39570. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39571. }
  39572. }
  39573. if (parsedGeometry.matricesWeights) {
  39574. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39575. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39576. }
  39577. if (parsedGeometry.matricesWeightsExtra) {
  39578. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39579. }
  39580. mesh.setIndices(parsedGeometry.indices, null);
  39581. }
  39582. // SubMeshes
  39583. if (parsedGeometry.subMeshes) {
  39584. mesh.subMeshes = [];
  39585. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39586. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39587. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39588. }
  39589. }
  39590. // Flat shading
  39591. if (mesh._shouldGenerateFlatShading) {
  39592. mesh.convertToFlatShadedMesh();
  39593. delete mesh._shouldGenerateFlatShading;
  39594. }
  39595. // Update
  39596. mesh.computeWorldMatrix(true);
  39597. // Octree
  39598. var sceneOctree = scene.selectionOctree;
  39599. if (sceneOctree !== undefined && sceneOctree !== null) {
  39600. sceneOctree.addMesh(mesh);
  39601. }
  39602. };
  39603. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39604. var epsilon = 1e-3;
  39605. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39606. return;
  39607. }
  39608. var noInfluenceBoneIndex = 0.0;
  39609. if (parsedGeometry.skeletonId > -1) {
  39610. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39611. if (!skeleton) {
  39612. return;
  39613. }
  39614. noInfluenceBoneIndex = skeleton.bones.length;
  39615. }
  39616. else {
  39617. return;
  39618. }
  39619. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39620. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39621. var matricesWeights = parsedGeometry.matricesWeights;
  39622. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39623. var influencers = parsedGeometry.numBoneInfluencer;
  39624. var size = matricesWeights.length;
  39625. for (var i = 0; i < size; i += 4) {
  39626. var weight = 0.0;
  39627. var firstZeroWeight = -1;
  39628. for (var j = 0; j < 4; j++) {
  39629. var w = matricesWeights[i + j];
  39630. weight += w;
  39631. if (w < epsilon && firstZeroWeight < 0) {
  39632. firstZeroWeight = j;
  39633. }
  39634. }
  39635. if (matricesWeightsExtra) {
  39636. for (var j = 0; j < 4; j++) {
  39637. var w = matricesWeightsExtra[i + j];
  39638. weight += w;
  39639. if (w < epsilon && firstZeroWeight < 0) {
  39640. firstZeroWeight = j + 4;
  39641. }
  39642. }
  39643. }
  39644. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39645. firstZeroWeight = influencers - 1;
  39646. }
  39647. if (weight > epsilon) {
  39648. var mweight = 1.0 / weight;
  39649. for (var j = 0; j < 4; j++) {
  39650. matricesWeights[i + j] *= mweight;
  39651. }
  39652. if (matricesWeightsExtra) {
  39653. for (var j = 0; j < 4; j++) {
  39654. matricesWeightsExtra[i + j] *= mweight;
  39655. }
  39656. }
  39657. }
  39658. else {
  39659. if (firstZeroWeight >= 4) {
  39660. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39661. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39662. }
  39663. else {
  39664. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39665. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39666. }
  39667. }
  39668. }
  39669. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39670. if (parsedGeometry.matricesWeightsExtra) {
  39671. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39672. }
  39673. };
  39674. /**
  39675. * Create a new geometry from persisted data (Using .babylon file format)
  39676. * @param parsedVertexData defines the persisted data
  39677. * @param scene defines the hosting scene
  39678. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39679. * @returns the new geometry object
  39680. */
  39681. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39682. if (scene.getGeometryByID(parsedVertexData.id)) {
  39683. return null; // null since geometry could be something else than a box...
  39684. }
  39685. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39686. if (BABYLON.Tags) {
  39687. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39688. }
  39689. if (parsedVertexData.delayLoadingFile) {
  39690. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39691. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39692. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39693. geometry._delayInfo = [];
  39694. if (parsedVertexData.hasUVs) {
  39695. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39696. }
  39697. if (parsedVertexData.hasUVs2) {
  39698. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39699. }
  39700. if (parsedVertexData.hasUVs3) {
  39701. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39702. }
  39703. if (parsedVertexData.hasUVs4) {
  39704. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39705. }
  39706. if (parsedVertexData.hasUVs5) {
  39707. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39708. }
  39709. if (parsedVertexData.hasUVs6) {
  39710. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39711. }
  39712. if (parsedVertexData.hasColors) {
  39713. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39714. }
  39715. if (parsedVertexData.hasMatricesIndices) {
  39716. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39717. }
  39718. if (parsedVertexData.hasMatricesWeights) {
  39719. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39720. }
  39721. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39722. }
  39723. else {
  39724. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39725. }
  39726. scene.pushGeometry(geometry, true);
  39727. return geometry;
  39728. };
  39729. return Geometry;
  39730. }());
  39731. BABYLON.Geometry = Geometry;
  39732. // Primitives
  39733. /// Abstract class
  39734. /**
  39735. * Abstract class used to provide common services for all typed geometries
  39736. * @hidden
  39737. */
  39738. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39739. __extends(_PrimitiveGeometry, _super);
  39740. /**
  39741. * Creates a new typed geometry
  39742. * @param id defines the unique ID of the geometry
  39743. * @param scene defines the hosting scene
  39744. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39745. * @param mesh defines the hosting mesh (can be null)
  39746. */
  39747. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39748. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39749. if (mesh === void 0) { mesh = null; }
  39750. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39751. _this._canBeRegenerated = _canBeRegenerated;
  39752. _this._beingRegenerated = true;
  39753. _this.regenerate();
  39754. _this._beingRegenerated = false;
  39755. return _this;
  39756. }
  39757. /**
  39758. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39759. * @returns true if the geometry can be regenerated
  39760. */
  39761. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39762. return this._canBeRegenerated;
  39763. };
  39764. /**
  39765. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39766. */
  39767. _PrimitiveGeometry.prototype.regenerate = function () {
  39768. if (!this._canBeRegenerated) {
  39769. return;
  39770. }
  39771. this._beingRegenerated = true;
  39772. this.setAllVerticesData(this._regenerateVertexData(), false);
  39773. this._beingRegenerated = false;
  39774. };
  39775. /**
  39776. * Clone the geometry
  39777. * @param id defines the unique ID of the new geometry
  39778. * @returns the new geometry
  39779. */
  39780. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39781. return _super.prototype.copy.call(this, id);
  39782. };
  39783. // overrides
  39784. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39785. if (!this._beingRegenerated) {
  39786. return;
  39787. }
  39788. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39789. };
  39790. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39791. if (!this._beingRegenerated) {
  39792. return;
  39793. }
  39794. _super.prototype.setVerticesData.call(this, kind, data, false);
  39795. };
  39796. // to override
  39797. /** @hidden */
  39798. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39799. throw new Error("Abstract method");
  39800. };
  39801. _PrimitiveGeometry.prototype.copy = function (id) {
  39802. throw new Error("Must be overriden in sub-classes.");
  39803. };
  39804. _PrimitiveGeometry.prototype.serialize = function () {
  39805. var serializationObject = _super.prototype.serialize.call(this);
  39806. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39807. return serializationObject;
  39808. };
  39809. return _PrimitiveGeometry;
  39810. }(Geometry));
  39811. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39812. /**
  39813. * Creates a ribbon geometry
  39814. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39815. */
  39816. var RibbonGeometry = /** @class */ (function (_super) {
  39817. __extends(RibbonGeometry, _super);
  39818. /**
  39819. * Creates a ribbon geometry
  39820. * @param id defines the unique ID of the geometry
  39821. * @param scene defines the hosting scene
  39822. * @param pathArray defines the array of paths to use
  39823. * @param closeArray defines if the last path and the first path must be joined
  39824. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39825. * @param offset defines the offset between points
  39826. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39827. * @param mesh defines the hosting mesh (can be null)
  39828. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39829. */
  39830. function RibbonGeometry(id, scene,
  39831. /**
  39832. * Defines the array of paths to use
  39833. */
  39834. pathArray,
  39835. /**
  39836. * Defines if the last and first points of each path in your pathArray must be joined
  39837. */
  39838. closeArray,
  39839. /**
  39840. * Defines if the last and first points of each path in your pathArray must be joined
  39841. */
  39842. closePath,
  39843. /**
  39844. * Defines the offset between points
  39845. */
  39846. offset, canBeRegenerated, mesh,
  39847. /**
  39848. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39849. */
  39850. side) {
  39851. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39852. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39853. _this.pathArray = pathArray;
  39854. _this.closeArray = closeArray;
  39855. _this.closePath = closePath;
  39856. _this.offset = offset;
  39857. _this.side = side;
  39858. return _this;
  39859. }
  39860. /** @hidden */
  39861. RibbonGeometry.prototype._regenerateVertexData = function () {
  39862. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39863. };
  39864. RibbonGeometry.prototype.copy = function (id) {
  39865. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39866. };
  39867. return RibbonGeometry;
  39868. }(_PrimitiveGeometry));
  39869. BABYLON.RibbonGeometry = RibbonGeometry;
  39870. /**
  39871. * Creates a box geometry
  39872. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39873. */
  39874. var BoxGeometry = /** @class */ (function (_super) {
  39875. __extends(BoxGeometry, _super);
  39876. /**
  39877. * Creates a box geometry
  39878. * @param id defines the unique ID of the geometry
  39879. * @param scene defines the hosting scene
  39880. * @param size defines the zise of the box (width, height and depth are the same)
  39881. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39882. * @param mesh defines the hosting mesh (can be null)
  39883. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39884. */
  39885. function BoxGeometry(id, scene,
  39886. /**
  39887. * Defines the zise of the box (width, height and depth are the same)
  39888. */
  39889. size, canBeRegenerated, mesh,
  39890. /**
  39891. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39892. */
  39893. side) {
  39894. if (mesh === void 0) { mesh = null; }
  39895. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39896. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39897. _this.size = size;
  39898. _this.side = side;
  39899. return _this;
  39900. }
  39901. BoxGeometry.prototype._regenerateVertexData = function () {
  39902. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39903. };
  39904. BoxGeometry.prototype.copy = function (id) {
  39905. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39906. };
  39907. BoxGeometry.prototype.serialize = function () {
  39908. var serializationObject = _super.prototype.serialize.call(this);
  39909. serializationObject.size = this.size;
  39910. return serializationObject;
  39911. };
  39912. BoxGeometry.Parse = function (parsedBox, scene) {
  39913. if (scene.getGeometryByID(parsedBox.id)) {
  39914. return null; // null since geometry could be something else than a box...
  39915. }
  39916. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39917. if (BABYLON.Tags) {
  39918. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39919. }
  39920. scene.pushGeometry(box, true);
  39921. return box;
  39922. };
  39923. return BoxGeometry;
  39924. }(_PrimitiveGeometry));
  39925. BABYLON.BoxGeometry = BoxGeometry;
  39926. /**
  39927. * Creates a sphere geometry
  39928. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39929. */
  39930. var SphereGeometry = /** @class */ (function (_super) {
  39931. __extends(SphereGeometry, _super);
  39932. /**
  39933. * Create a new sphere geometry
  39934. * @param id defines the unique ID of the geometry
  39935. * @param scene defines the hosting scene
  39936. * @param segments defines the number of segments to use to create the sphere
  39937. * @param diameter defines the diameter of the sphere
  39938. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39939. * @param mesh defines the hosting mesh (can be null)
  39940. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39941. */
  39942. function SphereGeometry(id, scene,
  39943. /**
  39944. * Defines the number of segments to use to create the sphere
  39945. */
  39946. segments,
  39947. /**
  39948. * Defines the diameter of the sphere
  39949. */
  39950. diameter, canBeRegenerated, mesh,
  39951. /**
  39952. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39953. */
  39954. side) {
  39955. if (mesh === void 0) { mesh = null; }
  39956. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39957. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39958. _this.segments = segments;
  39959. _this.diameter = diameter;
  39960. _this.side = side;
  39961. return _this;
  39962. }
  39963. SphereGeometry.prototype._regenerateVertexData = function () {
  39964. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39965. };
  39966. SphereGeometry.prototype.copy = function (id) {
  39967. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39968. };
  39969. SphereGeometry.prototype.serialize = function () {
  39970. var serializationObject = _super.prototype.serialize.call(this);
  39971. serializationObject.segments = this.segments;
  39972. serializationObject.diameter = this.diameter;
  39973. return serializationObject;
  39974. };
  39975. SphereGeometry.Parse = function (parsedSphere, scene) {
  39976. if (scene.getGeometryByID(parsedSphere.id)) {
  39977. return null; // null since geometry could be something else than a sphere...
  39978. }
  39979. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39980. if (BABYLON.Tags) {
  39981. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39982. }
  39983. scene.pushGeometry(sphere, true);
  39984. return sphere;
  39985. };
  39986. return SphereGeometry;
  39987. }(_PrimitiveGeometry));
  39988. BABYLON.SphereGeometry = SphereGeometry;
  39989. /**
  39990. * Creates a disc geometry
  39991. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39992. */
  39993. var DiscGeometry = /** @class */ (function (_super) {
  39994. __extends(DiscGeometry, _super);
  39995. /**
  39996. * Creates a new disc geometry
  39997. * @param id defines the unique ID of the geometry
  39998. * @param scene defines the hosting scene
  39999. * @param radius defines the radius of the disc
  40000. * @param tessellation defines the tesselation factor to apply to the disc
  40001. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40002. * @param mesh defines the hosting mesh (can be null)
  40003. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40004. */
  40005. function DiscGeometry(id, scene,
  40006. /**
  40007. * Defines the radius of the disc
  40008. */
  40009. radius,
  40010. /**
  40011. * Defines the tesselation factor to apply to the disc
  40012. */
  40013. tessellation, canBeRegenerated, mesh,
  40014. /**
  40015. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40016. */
  40017. side) {
  40018. if (mesh === void 0) { mesh = null; }
  40019. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40020. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40021. _this.radius = radius;
  40022. _this.tessellation = tessellation;
  40023. _this.side = side;
  40024. return _this;
  40025. }
  40026. DiscGeometry.prototype._regenerateVertexData = function () {
  40027. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40028. };
  40029. DiscGeometry.prototype.copy = function (id) {
  40030. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40031. };
  40032. return DiscGeometry;
  40033. }(_PrimitiveGeometry));
  40034. BABYLON.DiscGeometry = DiscGeometry;
  40035. /**
  40036. * Creates a new cylinder geometry
  40037. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40038. */
  40039. var CylinderGeometry = /** @class */ (function (_super) {
  40040. __extends(CylinderGeometry, _super);
  40041. /**
  40042. * Creates a new cylinder geometry
  40043. * @param id defines the unique ID of the geometry
  40044. * @param scene defines the hosting scene
  40045. * @param height defines the height of the cylinder
  40046. * @param diameterTop defines the diameter of the cylinder's top cap
  40047. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40048. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40049. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40050. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40051. * @param mesh defines the hosting mesh (can be null)
  40052. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40053. */
  40054. function CylinderGeometry(id, scene,
  40055. /**
  40056. * Defines the height of the cylinder
  40057. */
  40058. height,
  40059. /**
  40060. * Defines the diameter of the cylinder's top cap
  40061. */
  40062. diameterTop,
  40063. /**
  40064. * Defines the diameter of the cylinder's bottom cap
  40065. */
  40066. diameterBottom,
  40067. /**
  40068. * Defines the tessellation factor to apply to the cylinder
  40069. */
  40070. tessellation,
  40071. /**
  40072. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40073. */
  40074. subdivisions, canBeRegenerated, mesh,
  40075. /**
  40076. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40077. */
  40078. side) {
  40079. if (subdivisions === void 0) { subdivisions = 1; }
  40080. if (mesh === void 0) { mesh = null; }
  40081. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40082. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40083. _this.height = height;
  40084. _this.diameterTop = diameterTop;
  40085. _this.diameterBottom = diameterBottom;
  40086. _this.tessellation = tessellation;
  40087. _this.subdivisions = subdivisions;
  40088. _this.side = side;
  40089. return _this;
  40090. }
  40091. CylinderGeometry.prototype._regenerateVertexData = function () {
  40092. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40093. };
  40094. CylinderGeometry.prototype.copy = function (id) {
  40095. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40096. };
  40097. CylinderGeometry.prototype.serialize = function () {
  40098. var serializationObject = _super.prototype.serialize.call(this);
  40099. serializationObject.height = this.height;
  40100. serializationObject.diameterTop = this.diameterTop;
  40101. serializationObject.diameterBottom = this.diameterBottom;
  40102. serializationObject.tessellation = this.tessellation;
  40103. return serializationObject;
  40104. };
  40105. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40106. if (scene.getGeometryByID(parsedCylinder.id)) {
  40107. return null; // null since geometry could be something else than a cylinder...
  40108. }
  40109. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40110. if (BABYLON.Tags) {
  40111. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40112. }
  40113. scene.pushGeometry(cylinder, true);
  40114. return cylinder;
  40115. };
  40116. return CylinderGeometry;
  40117. }(_PrimitiveGeometry));
  40118. BABYLON.CylinderGeometry = CylinderGeometry;
  40119. /**
  40120. * Creates a new torus geometry
  40121. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40122. */
  40123. var TorusGeometry = /** @class */ (function (_super) {
  40124. __extends(TorusGeometry, _super);
  40125. /**
  40126. * Creates a new torus geometry
  40127. * @param id defines the unique ID of the geometry
  40128. * @param scene defines the hosting scene
  40129. * @param diameter defines the diameter of the torus
  40130. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40131. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40132. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40133. * @param mesh defines the hosting mesh (can be null)
  40134. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40135. */
  40136. function TorusGeometry(id, scene,
  40137. /**
  40138. * Defines the diameter of the torus
  40139. */
  40140. diameter,
  40141. /**
  40142. * Defines the thickness of the torus (ie. internal diameter)
  40143. */
  40144. thickness,
  40145. /**
  40146. * Defines the tesselation factor to apply to the torus
  40147. */
  40148. tessellation, canBeRegenerated, mesh,
  40149. /**
  40150. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40151. */
  40152. side) {
  40153. if (mesh === void 0) { mesh = null; }
  40154. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40155. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40156. _this.diameter = diameter;
  40157. _this.thickness = thickness;
  40158. _this.tessellation = tessellation;
  40159. _this.side = side;
  40160. return _this;
  40161. }
  40162. TorusGeometry.prototype._regenerateVertexData = function () {
  40163. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40164. };
  40165. TorusGeometry.prototype.copy = function (id) {
  40166. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40167. };
  40168. TorusGeometry.prototype.serialize = function () {
  40169. var serializationObject = _super.prototype.serialize.call(this);
  40170. serializationObject.diameter = this.diameter;
  40171. serializationObject.thickness = this.thickness;
  40172. serializationObject.tessellation = this.tessellation;
  40173. return serializationObject;
  40174. };
  40175. TorusGeometry.Parse = function (parsedTorus, scene) {
  40176. if (scene.getGeometryByID(parsedTorus.id)) {
  40177. return null; // null since geometry could be something else than a torus...
  40178. }
  40179. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40180. if (BABYLON.Tags) {
  40181. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40182. }
  40183. scene.pushGeometry(torus, true);
  40184. return torus;
  40185. };
  40186. return TorusGeometry;
  40187. }(_PrimitiveGeometry));
  40188. BABYLON.TorusGeometry = TorusGeometry;
  40189. /**
  40190. * Creates a new ground geometry
  40191. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40192. */
  40193. var GroundGeometry = /** @class */ (function (_super) {
  40194. __extends(GroundGeometry, _super);
  40195. /**
  40196. * Creates a new ground geometry
  40197. * @param id defines the unique ID of the geometry
  40198. * @param scene defines the hosting scene
  40199. * @param width defines the width of the ground
  40200. * @param height defines the height of the ground
  40201. * @param subdivisions defines the subdivisions to apply to the ground
  40202. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40203. * @param mesh defines the hosting mesh (can be null)
  40204. */
  40205. function GroundGeometry(id, scene,
  40206. /**
  40207. * Defines the width of the ground
  40208. */
  40209. width,
  40210. /**
  40211. * Defines the height of the ground
  40212. */
  40213. height,
  40214. /**
  40215. * Defines the subdivisions to apply to the ground
  40216. */
  40217. subdivisions, canBeRegenerated, mesh) {
  40218. if (mesh === void 0) { mesh = null; }
  40219. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40220. _this.width = width;
  40221. _this.height = height;
  40222. _this.subdivisions = subdivisions;
  40223. return _this;
  40224. }
  40225. GroundGeometry.prototype._regenerateVertexData = function () {
  40226. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40227. };
  40228. GroundGeometry.prototype.copy = function (id) {
  40229. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40230. };
  40231. GroundGeometry.prototype.serialize = function () {
  40232. var serializationObject = _super.prototype.serialize.call(this);
  40233. serializationObject.width = this.width;
  40234. serializationObject.height = this.height;
  40235. serializationObject.subdivisions = this.subdivisions;
  40236. return serializationObject;
  40237. };
  40238. GroundGeometry.Parse = function (parsedGround, scene) {
  40239. if (scene.getGeometryByID(parsedGround.id)) {
  40240. return null; // null since geometry could be something else than a ground...
  40241. }
  40242. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40243. if (BABYLON.Tags) {
  40244. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40245. }
  40246. scene.pushGeometry(ground, true);
  40247. return ground;
  40248. };
  40249. return GroundGeometry;
  40250. }(_PrimitiveGeometry));
  40251. BABYLON.GroundGeometry = GroundGeometry;
  40252. /**
  40253. * Creates a tiled ground geometry
  40254. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40255. */
  40256. var TiledGroundGeometry = /** @class */ (function (_super) {
  40257. __extends(TiledGroundGeometry, _super);
  40258. /**
  40259. * Creates a tiled ground geometry
  40260. * @param id defines the unique ID of the geometry
  40261. * @param scene defines the hosting scene
  40262. * @param xmin defines the minimum value on X axis
  40263. * @param zmin defines the minimum value on Z axis
  40264. * @param xmax defines the maximum value on X axis
  40265. * @param zmax defines the maximum value on Z axis
  40266. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40267. * @param precision defines the precision to use when computing the tiles
  40268. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40269. * @param mesh defines the hosting mesh (can be null)
  40270. */
  40271. function TiledGroundGeometry(id, scene,
  40272. /**
  40273. * Defines the minimum value on X axis
  40274. */
  40275. xmin,
  40276. /**
  40277. * Defines the minimum value on Z axis
  40278. */
  40279. zmin,
  40280. /**
  40281. * Defines the maximum value on X axis
  40282. */
  40283. xmax,
  40284. /**
  40285. * Defines the maximum value on Z axis
  40286. */
  40287. zmax,
  40288. /**
  40289. * Defines the subdivisions to apply to the ground
  40290. */
  40291. subdivisions,
  40292. /**
  40293. * Defines the precision to use when computing the tiles
  40294. */
  40295. precision, canBeRegenerated, mesh) {
  40296. if (mesh === void 0) { mesh = null; }
  40297. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40298. _this.xmin = xmin;
  40299. _this.zmin = zmin;
  40300. _this.xmax = xmax;
  40301. _this.zmax = zmax;
  40302. _this.subdivisions = subdivisions;
  40303. _this.precision = precision;
  40304. return _this;
  40305. }
  40306. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40307. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40308. };
  40309. TiledGroundGeometry.prototype.copy = function (id) {
  40310. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40311. };
  40312. return TiledGroundGeometry;
  40313. }(_PrimitiveGeometry));
  40314. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40315. /**
  40316. * Creates a plane geometry
  40317. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40318. */
  40319. var PlaneGeometry = /** @class */ (function (_super) {
  40320. __extends(PlaneGeometry, _super);
  40321. /**
  40322. * Creates a plane geometry
  40323. * @param id defines the unique ID of the geometry
  40324. * @param scene defines the hosting scene
  40325. * @param size defines the size of the plane (width === height)
  40326. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40327. * @param mesh defines the hosting mesh (can be null)
  40328. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40329. */
  40330. function PlaneGeometry(id, scene,
  40331. /**
  40332. * Defines the size of the plane (width === height)
  40333. */
  40334. size, canBeRegenerated, mesh,
  40335. /**
  40336. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40337. */
  40338. side) {
  40339. if (mesh === void 0) { mesh = null; }
  40340. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40341. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40342. _this.size = size;
  40343. _this.side = side;
  40344. return _this;
  40345. }
  40346. PlaneGeometry.prototype._regenerateVertexData = function () {
  40347. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40348. };
  40349. PlaneGeometry.prototype.copy = function (id) {
  40350. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40351. };
  40352. PlaneGeometry.prototype.serialize = function () {
  40353. var serializationObject = _super.prototype.serialize.call(this);
  40354. serializationObject.size = this.size;
  40355. return serializationObject;
  40356. };
  40357. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40358. if (scene.getGeometryByID(parsedPlane.id)) {
  40359. return null; // null since geometry could be something else than a ground...
  40360. }
  40361. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40362. if (BABYLON.Tags) {
  40363. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40364. }
  40365. scene.pushGeometry(plane, true);
  40366. return plane;
  40367. };
  40368. return PlaneGeometry;
  40369. }(_PrimitiveGeometry));
  40370. BABYLON.PlaneGeometry = PlaneGeometry;
  40371. /**
  40372. * Creates a torus knot geometry
  40373. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40374. */
  40375. var TorusKnotGeometry = /** @class */ (function (_super) {
  40376. __extends(TorusKnotGeometry, _super);
  40377. /**
  40378. * Creates a torus knot geometry
  40379. * @param id defines the unique ID of the geometry
  40380. * @param scene defines the hosting scene
  40381. * @param radius defines the radius of the torus knot
  40382. * @param tube defines the thickness of the torus knot tube
  40383. * @param radialSegments defines the number of radial segments
  40384. * @param tubularSegments defines the number of tubular segments
  40385. * @param p defines the first number of windings
  40386. * @param q defines the second number of windings
  40387. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40388. * @param mesh defines the hosting mesh (can be null)
  40389. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40390. */
  40391. function TorusKnotGeometry(id, scene,
  40392. /**
  40393. * Defines the radius of the torus knot
  40394. */
  40395. radius,
  40396. /**
  40397. * Defines the thickness of the torus knot tube
  40398. */
  40399. tube,
  40400. /**
  40401. * Defines the number of radial segments
  40402. */
  40403. radialSegments,
  40404. /**
  40405. * Defines the number of tubular segments
  40406. */
  40407. tubularSegments,
  40408. /**
  40409. * Defines the first number of windings
  40410. */
  40411. p,
  40412. /**
  40413. * Defines the second number of windings
  40414. */
  40415. q, canBeRegenerated, mesh,
  40416. /**
  40417. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40418. */
  40419. side) {
  40420. if (mesh === void 0) { mesh = null; }
  40421. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40422. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40423. _this.radius = radius;
  40424. _this.tube = tube;
  40425. _this.radialSegments = radialSegments;
  40426. _this.tubularSegments = tubularSegments;
  40427. _this.p = p;
  40428. _this.q = q;
  40429. _this.side = side;
  40430. return _this;
  40431. }
  40432. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40433. 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 });
  40434. };
  40435. TorusKnotGeometry.prototype.copy = function (id) {
  40436. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40437. };
  40438. TorusKnotGeometry.prototype.serialize = function () {
  40439. var serializationObject = _super.prototype.serialize.call(this);
  40440. serializationObject.radius = this.radius;
  40441. serializationObject.tube = this.tube;
  40442. serializationObject.radialSegments = this.radialSegments;
  40443. serializationObject.tubularSegments = this.tubularSegments;
  40444. serializationObject.p = this.p;
  40445. serializationObject.q = this.q;
  40446. return serializationObject;
  40447. };
  40448. ;
  40449. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40450. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40451. return null; // null since geometry could be something else than a ground...
  40452. }
  40453. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40454. if (BABYLON.Tags) {
  40455. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40456. }
  40457. scene.pushGeometry(torusKnot, true);
  40458. return torusKnot;
  40459. };
  40460. return TorusKnotGeometry;
  40461. }(_PrimitiveGeometry));
  40462. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40463. //}
  40464. })(BABYLON || (BABYLON = {}));
  40465. //# sourceMappingURL=babylon.geometry.js.map
  40466. var BABYLON;
  40467. (function (BABYLON) {
  40468. /**
  40469. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40470. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40471. */
  40472. var PostProcessManager = /** @class */ (function () {
  40473. /**
  40474. * Creates a new instance PostProcess
  40475. * @param scene The scene that the post process is associated with.
  40476. */
  40477. function PostProcessManager(scene) {
  40478. this._vertexBuffers = {};
  40479. this._scene = scene;
  40480. }
  40481. PostProcessManager.prototype._prepareBuffers = function () {
  40482. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40483. return;
  40484. }
  40485. // VBO
  40486. var vertices = [];
  40487. vertices.push(1, 1);
  40488. vertices.push(-1, 1);
  40489. vertices.push(-1, -1);
  40490. vertices.push(1, -1);
  40491. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40492. this._buildIndexBuffer();
  40493. };
  40494. PostProcessManager.prototype._buildIndexBuffer = function () {
  40495. // Indices
  40496. var indices = [];
  40497. indices.push(0);
  40498. indices.push(1);
  40499. indices.push(2);
  40500. indices.push(0);
  40501. indices.push(2);
  40502. indices.push(3);
  40503. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40504. };
  40505. /**
  40506. * Rebuilds the vertex buffers of the manager.
  40507. */
  40508. PostProcessManager.prototype._rebuild = function () {
  40509. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40510. if (!vb) {
  40511. return;
  40512. }
  40513. vb._rebuild();
  40514. this._buildIndexBuffer();
  40515. };
  40516. // Methods
  40517. /**
  40518. * Prepares a frame to be run through a post process.
  40519. * @param sourceTexture The input texture to the post procesess. (default: null)
  40520. * @param postProcesses An array of post processes to be run. (default: null)
  40521. * @returns True if the post processes were able to be run.
  40522. */
  40523. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40524. if (sourceTexture === void 0) { sourceTexture = null; }
  40525. if (postProcesses === void 0) { postProcesses = null; }
  40526. var camera = this._scene.activeCamera;
  40527. if (!camera) {
  40528. return false;
  40529. }
  40530. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40531. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40532. return false;
  40533. }
  40534. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40535. return true;
  40536. };
  40537. /**
  40538. * Manually render a set of post processes to a texture.
  40539. * @param postProcesses An array of post processes to be run.
  40540. * @param targetTexture The target texture to render to.
  40541. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40542. */
  40543. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40544. if (targetTexture === void 0) { targetTexture = null; }
  40545. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40546. var engine = this._scene.getEngine();
  40547. for (var index = 0; index < postProcesses.length; index++) {
  40548. if (index < postProcesses.length - 1) {
  40549. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40550. }
  40551. else {
  40552. if (targetTexture) {
  40553. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40554. }
  40555. else {
  40556. engine.restoreDefaultFramebuffer();
  40557. }
  40558. }
  40559. var pp = postProcesses[index];
  40560. var effect = pp.apply();
  40561. if (effect) {
  40562. pp.onBeforeRenderObservable.notifyObservers(effect);
  40563. // VBOs
  40564. this._prepareBuffers();
  40565. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40566. // Draw order
  40567. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40568. pp.onAfterRenderObservable.notifyObservers(effect);
  40569. }
  40570. }
  40571. // Restore depth buffer
  40572. engine.setDepthBuffer(true);
  40573. engine.setDepthWrite(true);
  40574. };
  40575. /**
  40576. * Finalize the result of the output of the postprocesses.
  40577. * @param doNotPresent If true the result will not be displayed to the screen.
  40578. * @param targetTexture The target texture to render to.
  40579. * @param faceIndex The index of the face to bind the target texture to.
  40580. * @param postProcesses The array of post processes to render.
  40581. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40582. */
  40583. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40584. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40585. var camera = this._scene.activeCamera;
  40586. if (!camera) {
  40587. return;
  40588. }
  40589. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40590. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40591. return;
  40592. }
  40593. var engine = this._scene.getEngine();
  40594. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40595. var pp = postProcesses[index];
  40596. if (index < len - 1) {
  40597. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40598. }
  40599. else {
  40600. if (targetTexture) {
  40601. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40602. pp._outputTexture = targetTexture;
  40603. }
  40604. else {
  40605. engine.restoreDefaultFramebuffer();
  40606. pp._outputTexture = null;
  40607. }
  40608. }
  40609. if (doNotPresent) {
  40610. break;
  40611. }
  40612. var effect = pp.apply();
  40613. if (effect) {
  40614. pp.onBeforeRenderObservable.notifyObservers(effect);
  40615. // VBOs
  40616. this._prepareBuffers();
  40617. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40618. // Draw order
  40619. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40620. pp.onAfterRenderObservable.notifyObservers(effect);
  40621. }
  40622. }
  40623. // Restore states
  40624. engine.setDepthBuffer(true);
  40625. engine.setDepthWrite(true);
  40626. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40627. };
  40628. /**
  40629. * Disposes of the post process manager.
  40630. */
  40631. PostProcessManager.prototype.dispose = function () {
  40632. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40633. if (buffer) {
  40634. buffer.dispose();
  40635. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40636. }
  40637. if (this._indexBuffer) {
  40638. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40639. this._indexBuffer = null;
  40640. }
  40641. };
  40642. return PostProcessManager;
  40643. }());
  40644. BABYLON.PostProcessManager = PostProcessManager;
  40645. })(BABYLON || (BABYLON = {}));
  40646. //# sourceMappingURL=babylon.postProcessManager.js.map
  40647. var BABYLON;
  40648. (function (BABYLON) {
  40649. /**
  40650. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40651. */
  40652. var PerformanceMonitor = /** @class */ (function () {
  40653. /**
  40654. * constructor
  40655. * @param frameSampleSize The number of samples required to saturate the sliding window
  40656. */
  40657. function PerformanceMonitor(frameSampleSize) {
  40658. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40659. this._enabled = true;
  40660. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40661. }
  40662. /**
  40663. * Samples current frame
  40664. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40665. */
  40666. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40667. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40668. if (!this._enabled)
  40669. return;
  40670. if (this._lastFrameTimeMs != null) {
  40671. var dt = timeMs - this._lastFrameTimeMs;
  40672. this._rollingFrameTime.add(dt);
  40673. }
  40674. this._lastFrameTimeMs = timeMs;
  40675. };
  40676. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40677. /**
  40678. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40679. * @return Average frame time in milliseconds
  40680. */
  40681. get: function () {
  40682. return this._rollingFrameTime.average;
  40683. },
  40684. enumerable: true,
  40685. configurable: true
  40686. });
  40687. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40688. /**
  40689. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40690. * @return Frame time variance in milliseconds squared
  40691. */
  40692. get: function () {
  40693. return this._rollingFrameTime.variance;
  40694. },
  40695. enumerable: true,
  40696. configurable: true
  40697. });
  40698. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40699. /**
  40700. * Returns the frame time of the most recent frame
  40701. * @return Frame time in milliseconds
  40702. */
  40703. get: function () {
  40704. return this._rollingFrameTime.history(0);
  40705. },
  40706. enumerable: true,
  40707. configurable: true
  40708. });
  40709. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40710. /**
  40711. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40712. * @return Framerate in frames per second
  40713. */
  40714. get: function () {
  40715. return 1000.0 / this._rollingFrameTime.average;
  40716. },
  40717. enumerable: true,
  40718. configurable: true
  40719. });
  40720. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40721. /**
  40722. * Returns the average framerate in frames per second using the most recent frame time
  40723. * @return Framerate in frames per second
  40724. */
  40725. get: function () {
  40726. var history = this._rollingFrameTime.history(0);
  40727. if (history === 0) {
  40728. return 0;
  40729. }
  40730. return 1000.0 / history;
  40731. },
  40732. enumerable: true,
  40733. configurable: true
  40734. });
  40735. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40736. /**
  40737. * Returns true if enough samples have been taken to completely fill the sliding window
  40738. * @return true if saturated
  40739. */
  40740. get: function () {
  40741. return this._rollingFrameTime.isSaturated();
  40742. },
  40743. enumerable: true,
  40744. configurable: true
  40745. });
  40746. /**
  40747. * Enables contributions to the sliding window sample set
  40748. */
  40749. PerformanceMonitor.prototype.enable = function () {
  40750. this._enabled = true;
  40751. };
  40752. /**
  40753. * Disables contributions to the sliding window sample set
  40754. * Samples will not be interpolated over the disabled period
  40755. */
  40756. PerformanceMonitor.prototype.disable = function () {
  40757. this._enabled = false;
  40758. //clear last sample to avoid interpolating over the disabled period when next enabled
  40759. this._lastFrameTimeMs = null;
  40760. };
  40761. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40762. /**
  40763. * Returns true if sampling is enabled
  40764. * @return true if enabled
  40765. */
  40766. get: function () {
  40767. return this._enabled;
  40768. },
  40769. enumerable: true,
  40770. configurable: true
  40771. });
  40772. /**
  40773. * Resets performance monitor
  40774. */
  40775. PerformanceMonitor.prototype.reset = function () {
  40776. //clear last sample to avoid interpolating over the disabled period when next enabled
  40777. this._lastFrameTimeMs = null;
  40778. //wipe record
  40779. this._rollingFrameTime.reset();
  40780. };
  40781. return PerformanceMonitor;
  40782. }());
  40783. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40784. /**
  40785. * RollingAverage
  40786. *
  40787. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40788. */
  40789. var RollingAverage = /** @class */ (function () {
  40790. /**
  40791. * constructor
  40792. * @param length The number of samples required to saturate the sliding window
  40793. */
  40794. function RollingAverage(length) {
  40795. this._samples = new Array(length);
  40796. this.reset();
  40797. }
  40798. /**
  40799. * Adds a sample to the sample set
  40800. * @param v The sample value
  40801. */
  40802. RollingAverage.prototype.add = function (v) {
  40803. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40804. var delta;
  40805. //we need to check if we've already wrapped round
  40806. if (this.isSaturated()) {
  40807. //remove bottom of stack from mean
  40808. var bottomValue = this._samples[this._pos];
  40809. delta = bottomValue - this.average;
  40810. this.average -= delta / (this._sampleCount - 1);
  40811. this._m2 -= delta * (bottomValue - this.average);
  40812. }
  40813. else {
  40814. this._sampleCount++;
  40815. }
  40816. //add new value to mean
  40817. delta = v - this.average;
  40818. this.average += delta / (this._sampleCount);
  40819. this._m2 += delta * (v - this.average);
  40820. //set the new variance
  40821. this.variance = this._m2 / (this._sampleCount - 1);
  40822. this._samples[this._pos] = v;
  40823. this._pos++;
  40824. this._pos %= this._samples.length; //positive wrap around
  40825. };
  40826. /**
  40827. * Returns previously added values or null if outside of history or outside the sliding window domain
  40828. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40829. * @return Value previously recorded with add() or null if outside of range
  40830. */
  40831. RollingAverage.prototype.history = function (i) {
  40832. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40833. return 0;
  40834. }
  40835. var i0 = this._wrapPosition(this._pos - 1.0);
  40836. return this._samples[this._wrapPosition(i0 - i)];
  40837. };
  40838. /**
  40839. * Returns true if enough samples have been taken to completely fill the sliding window
  40840. * @return true if sample-set saturated
  40841. */
  40842. RollingAverage.prototype.isSaturated = function () {
  40843. return this._sampleCount >= this._samples.length;
  40844. };
  40845. /**
  40846. * Resets the rolling average (equivalent to 0 samples taken so far)
  40847. */
  40848. RollingAverage.prototype.reset = function () {
  40849. this.average = 0;
  40850. this.variance = 0;
  40851. this._sampleCount = 0;
  40852. this._pos = 0;
  40853. this._m2 = 0;
  40854. };
  40855. /**
  40856. * Wraps a value around the sample range boundaries
  40857. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40858. * @return Wrapped position in sample range
  40859. */
  40860. RollingAverage.prototype._wrapPosition = function (i) {
  40861. var max = this._samples.length;
  40862. return ((i % max) + max) % max;
  40863. };
  40864. return RollingAverage;
  40865. }());
  40866. BABYLON.RollingAverage = RollingAverage;
  40867. })(BABYLON || (BABYLON = {}));
  40868. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40869. var BABYLON;
  40870. (function (BABYLON) {
  40871. /**
  40872. * This groups together the common properties used for image processing either in direct forward pass
  40873. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40874. * or not.
  40875. */
  40876. var ImageProcessingConfiguration = /** @class */ (function () {
  40877. function ImageProcessingConfiguration() {
  40878. /**
  40879. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40880. */
  40881. this.colorCurves = new BABYLON.ColorCurves();
  40882. this._colorCurvesEnabled = false;
  40883. this._colorGradingEnabled = false;
  40884. this._colorGradingWithGreenDepth = true;
  40885. this._colorGradingBGR = true;
  40886. this._exposure = 1.0;
  40887. this._toneMappingEnabled = false;
  40888. this._contrast = 1.0;
  40889. /**
  40890. * Vignette stretch size.
  40891. */
  40892. this.vignetteStretch = 0;
  40893. /**
  40894. * Vignette centre X Offset.
  40895. */
  40896. this.vignetteCentreX = 0;
  40897. /**
  40898. * Vignette centre Y Offset.
  40899. */
  40900. this.vignetteCentreY = 0;
  40901. /**
  40902. * Vignette weight or intensity of the vignette effect.
  40903. */
  40904. this.vignetteWeight = 1.5;
  40905. /**
  40906. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40907. * if vignetteEnabled is set to true.
  40908. */
  40909. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40910. /**
  40911. * Camera field of view used by the Vignette effect.
  40912. */
  40913. this.vignetteCameraFov = 0.5;
  40914. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40915. this._vignetteEnabled = false;
  40916. this._applyByPostProcess = false;
  40917. this._isEnabled = true;
  40918. /**
  40919. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40920. */
  40921. this.onUpdateParameters = new BABYLON.Observable();
  40922. }
  40923. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40924. /**
  40925. * Gets wether the color curves effect is enabled.
  40926. */
  40927. get: function () {
  40928. return this._colorCurvesEnabled;
  40929. },
  40930. /**
  40931. * Sets wether the color curves effect is enabled.
  40932. */
  40933. set: function (value) {
  40934. if (this._colorCurvesEnabled === value) {
  40935. return;
  40936. }
  40937. this._colorCurvesEnabled = value;
  40938. this._updateParameters();
  40939. },
  40940. enumerable: true,
  40941. configurable: true
  40942. });
  40943. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40944. /**
  40945. * Gets wether the color grading effect is enabled.
  40946. */
  40947. get: function () {
  40948. return this._colorGradingEnabled;
  40949. },
  40950. /**
  40951. * Sets wether the color grading effect is enabled.
  40952. */
  40953. set: function (value) {
  40954. if (this._colorGradingEnabled === value) {
  40955. return;
  40956. }
  40957. this._colorGradingEnabled = value;
  40958. this._updateParameters();
  40959. },
  40960. enumerable: true,
  40961. configurable: true
  40962. });
  40963. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40964. /**
  40965. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40966. */
  40967. get: function () {
  40968. return this._colorGradingWithGreenDepth;
  40969. },
  40970. /**
  40971. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40972. */
  40973. set: function (value) {
  40974. if (this._colorGradingWithGreenDepth === value) {
  40975. return;
  40976. }
  40977. this._colorGradingWithGreenDepth = value;
  40978. this._updateParameters();
  40979. },
  40980. enumerable: true,
  40981. configurable: true
  40982. });
  40983. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40984. /**
  40985. * Gets wether the color grading texture contains BGR values.
  40986. */
  40987. get: function () {
  40988. return this._colorGradingBGR;
  40989. },
  40990. /**
  40991. * Sets wether the color grading texture contains BGR values.
  40992. */
  40993. set: function (value) {
  40994. if (this._colorGradingBGR === value) {
  40995. return;
  40996. }
  40997. this._colorGradingBGR = value;
  40998. this._updateParameters();
  40999. },
  41000. enumerable: true,
  41001. configurable: true
  41002. });
  41003. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41004. /**
  41005. * Gets the Exposure used in the effect.
  41006. */
  41007. get: function () {
  41008. return this._exposure;
  41009. },
  41010. /**
  41011. * Sets the Exposure used in the effect.
  41012. */
  41013. set: function (value) {
  41014. if (this._exposure === value) {
  41015. return;
  41016. }
  41017. this._exposure = value;
  41018. this._updateParameters();
  41019. },
  41020. enumerable: true,
  41021. configurable: true
  41022. });
  41023. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41024. /**
  41025. * Gets wether the tone mapping effect is enabled.
  41026. */
  41027. get: function () {
  41028. return this._toneMappingEnabled;
  41029. },
  41030. /**
  41031. * Sets wether the tone mapping effect is enabled.
  41032. */
  41033. set: function (value) {
  41034. if (this._toneMappingEnabled === value) {
  41035. return;
  41036. }
  41037. this._toneMappingEnabled = value;
  41038. this._updateParameters();
  41039. },
  41040. enumerable: true,
  41041. configurable: true
  41042. });
  41043. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41044. /**
  41045. * Gets the contrast used in the effect.
  41046. */
  41047. get: function () {
  41048. return this._contrast;
  41049. },
  41050. /**
  41051. * Sets the contrast used in the effect.
  41052. */
  41053. set: function (value) {
  41054. if (this._contrast === value) {
  41055. return;
  41056. }
  41057. this._contrast = value;
  41058. this._updateParameters();
  41059. },
  41060. enumerable: true,
  41061. configurable: true
  41062. });
  41063. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41064. /**
  41065. * Gets the vignette blend mode allowing different kind of effect.
  41066. */
  41067. get: function () {
  41068. return this._vignetteBlendMode;
  41069. },
  41070. /**
  41071. * Sets the vignette blend mode allowing different kind of effect.
  41072. */
  41073. set: function (value) {
  41074. if (this._vignetteBlendMode === value) {
  41075. return;
  41076. }
  41077. this._vignetteBlendMode = value;
  41078. this._updateParameters();
  41079. },
  41080. enumerable: true,
  41081. configurable: true
  41082. });
  41083. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41084. /**
  41085. * Gets wether the vignette effect is enabled.
  41086. */
  41087. get: function () {
  41088. return this._vignetteEnabled;
  41089. },
  41090. /**
  41091. * Sets wether the vignette effect is enabled.
  41092. */
  41093. set: function (value) {
  41094. if (this._vignetteEnabled === value) {
  41095. return;
  41096. }
  41097. this._vignetteEnabled = value;
  41098. this._updateParameters();
  41099. },
  41100. enumerable: true,
  41101. configurable: true
  41102. });
  41103. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41104. /**
  41105. * Gets wether the image processing is applied through a post process or not.
  41106. */
  41107. get: function () {
  41108. return this._applyByPostProcess;
  41109. },
  41110. /**
  41111. * Sets wether the image processing is applied through a post process or not.
  41112. */
  41113. set: function (value) {
  41114. if (this._applyByPostProcess === value) {
  41115. return;
  41116. }
  41117. this._applyByPostProcess = value;
  41118. this._updateParameters();
  41119. },
  41120. enumerable: true,
  41121. configurable: true
  41122. });
  41123. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41124. /**
  41125. * Gets wether the image processing is enabled or not.
  41126. */
  41127. get: function () {
  41128. return this._isEnabled;
  41129. },
  41130. /**
  41131. * Sets wether the image processing is enabled or not.
  41132. */
  41133. set: function (value) {
  41134. if (this._isEnabled === value) {
  41135. return;
  41136. }
  41137. this._isEnabled = value;
  41138. this._updateParameters();
  41139. },
  41140. enumerable: true,
  41141. configurable: true
  41142. });
  41143. /**
  41144. * Method called each time the image processing information changes requires to recompile the effect.
  41145. */
  41146. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41147. this.onUpdateParameters.notifyObservers(this);
  41148. };
  41149. ImageProcessingConfiguration.prototype.getClassName = function () {
  41150. return "ImageProcessingConfiguration";
  41151. };
  41152. /**
  41153. * Prepare the list of uniforms associated with the Image Processing effects.
  41154. * @param uniformsList The list of uniforms used in the effect
  41155. * @param defines the list of defines currently in use
  41156. */
  41157. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41158. if (defines.EXPOSURE) {
  41159. uniforms.push("exposureLinear");
  41160. }
  41161. if (defines.CONTRAST) {
  41162. uniforms.push("contrast");
  41163. }
  41164. if (defines.COLORGRADING) {
  41165. uniforms.push("colorTransformSettings");
  41166. }
  41167. if (defines.VIGNETTE) {
  41168. uniforms.push("vInverseScreenSize");
  41169. uniforms.push("vignetteSettings1");
  41170. uniforms.push("vignetteSettings2");
  41171. }
  41172. if (defines.COLORCURVES) {
  41173. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41174. }
  41175. };
  41176. /**
  41177. * Prepare the list of samplers associated with the Image Processing effects.
  41178. * @param uniformsList The list of uniforms used in the effect
  41179. * @param defines the list of defines currently in use
  41180. */
  41181. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41182. if (defines.COLORGRADING) {
  41183. samplersList.push("txColorTransform");
  41184. }
  41185. };
  41186. /**
  41187. * Prepare the list of defines associated to the shader.
  41188. * @param defines the list of defines to complete
  41189. */
  41190. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41191. if (forPostProcess === void 0) { forPostProcess = false; }
  41192. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41193. defines.VIGNETTE = false;
  41194. defines.TONEMAPPING = false;
  41195. defines.CONTRAST = false;
  41196. defines.EXPOSURE = false;
  41197. defines.COLORCURVES = false;
  41198. defines.COLORGRADING = false;
  41199. defines.COLORGRADING3D = false;
  41200. defines.IMAGEPROCESSING = false;
  41201. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41202. return;
  41203. }
  41204. defines.VIGNETTE = this.vignetteEnabled;
  41205. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41206. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41207. defines.TONEMAPPING = this.toneMappingEnabled;
  41208. defines.CONTRAST = (this.contrast !== 1.0);
  41209. defines.EXPOSURE = (this.exposure !== 1.0);
  41210. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41211. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41212. if (defines.COLORGRADING) {
  41213. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41214. }
  41215. else {
  41216. defines.COLORGRADING3D = false;
  41217. }
  41218. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41219. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41220. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41221. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41222. };
  41223. /**
  41224. * Returns true if all the image processing information are ready.
  41225. */
  41226. ImageProcessingConfiguration.prototype.isReady = function () {
  41227. // Color Grading texure can not be none blocking.
  41228. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41229. };
  41230. /**
  41231. * Binds the image processing to the shader.
  41232. * @param effect The effect to bind to
  41233. */
  41234. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41235. if (aspectRatio === void 0) { aspectRatio = 1; }
  41236. // Color Curves
  41237. if (this._colorCurvesEnabled && this.colorCurves) {
  41238. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41239. }
  41240. // Vignette
  41241. if (this._vignetteEnabled) {
  41242. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41243. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41244. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41245. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41246. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41247. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41248. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41249. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41250. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41251. var vignettePower = -2.0 * this.vignetteWeight;
  41252. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41253. }
  41254. // Exposure
  41255. effect.setFloat("exposureLinear", this.exposure);
  41256. // Contrast
  41257. effect.setFloat("contrast", this.contrast);
  41258. // Color transform settings
  41259. if (this.colorGradingTexture) {
  41260. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41261. var textureSize = this.colorGradingTexture.getSize().height;
  41262. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41263. 0.5 / textureSize, // textureOffset
  41264. textureSize, // textureSize
  41265. this.colorGradingTexture.level // weight
  41266. );
  41267. }
  41268. };
  41269. /**
  41270. * Clones the current image processing instance.
  41271. * @return The cloned image processing
  41272. */
  41273. ImageProcessingConfiguration.prototype.clone = function () {
  41274. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41275. };
  41276. /**
  41277. * Serializes the current image processing instance to a json representation.
  41278. * @return a JSON representation
  41279. */
  41280. ImageProcessingConfiguration.prototype.serialize = function () {
  41281. return BABYLON.SerializationHelper.Serialize(this);
  41282. };
  41283. /**
  41284. * Parses the image processing from a json representation.
  41285. * @param source the JSON source to parse
  41286. * @return The parsed image processing
  41287. */
  41288. ImageProcessingConfiguration.Parse = function (source) {
  41289. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41290. };
  41291. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41292. /**
  41293. * Used to apply the vignette as a mix with the pixel color.
  41294. */
  41295. get: function () {
  41296. return this._VIGNETTEMODE_MULTIPLY;
  41297. },
  41298. enumerable: true,
  41299. configurable: true
  41300. });
  41301. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41302. /**
  41303. * Used to apply the vignette as a replacement of the pixel color.
  41304. */
  41305. get: function () {
  41306. return this._VIGNETTEMODE_OPAQUE;
  41307. },
  41308. enumerable: true,
  41309. configurable: true
  41310. });
  41311. // Static constants associated to the image processing.
  41312. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41313. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41314. __decorate([
  41315. BABYLON.serializeAsColorCurves()
  41316. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41317. __decorate([
  41318. BABYLON.serialize()
  41319. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41320. __decorate([
  41321. BABYLON.serializeAsTexture()
  41322. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41323. __decorate([
  41324. BABYLON.serialize()
  41325. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41326. __decorate([
  41327. BABYLON.serialize()
  41328. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41329. __decorate([
  41330. BABYLON.serialize()
  41331. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41332. __decorate([
  41333. BABYLON.serialize()
  41334. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41335. __decorate([
  41336. BABYLON.serialize()
  41337. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41338. __decorate([
  41339. BABYLON.serialize()
  41340. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41341. __decorate([
  41342. BABYLON.serialize()
  41343. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41344. __decorate([
  41345. BABYLON.serialize()
  41346. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41347. __decorate([
  41348. BABYLON.serialize()
  41349. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41350. __decorate([
  41351. BABYLON.serialize()
  41352. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41353. __decorate([
  41354. BABYLON.serializeAsColor4()
  41355. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41356. __decorate([
  41357. BABYLON.serialize()
  41358. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41359. __decorate([
  41360. BABYLON.serialize()
  41361. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41362. __decorate([
  41363. BABYLON.serialize()
  41364. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41365. __decorate([
  41366. BABYLON.serialize()
  41367. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41368. __decorate([
  41369. BABYLON.serialize()
  41370. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41371. return ImageProcessingConfiguration;
  41372. }());
  41373. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41374. })(BABYLON || (BABYLON = {}));
  41375. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41376. var BABYLON;
  41377. (function (BABYLON) {
  41378. /**
  41379. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41380. * It can help converting any input color in a desired output one. This can then be used to create effects
  41381. * from sepia, black and white to sixties or futuristic rendering...
  41382. *
  41383. * The only supported format is currently 3dl.
  41384. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41385. */
  41386. var ColorGradingTexture = /** @class */ (function (_super) {
  41387. __extends(ColorGradingTexture, _super);
  41388. /**
  41389. * Instantiates a ColorGradingTexture from the following parameters.
  41390. *
  41391. * @param url The location of the color gradind data (currently only supporting 3dl)
  41392. * @param scene The scene the texture will be used in
  41393. */
  41394. function ColorGradingTexture(url, scene) {
  41395. var _this = _super.call(this, scene) || this;
  41396. if (!url) {
  41397. return _this;
  41398. }
  41399. _this._engine = scene.getEngine();
  41400. _this._textureMatrix = BABYLON.Matrix.Identity();
  41401. _this.name = url;
  41402. _this.url = url;
  41403. _this.hasAlpha = false;
  41404. _this.isCube = false;
  41405. _this.is3D = _this._engine.webGLVersion > 1;
  41406. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41407. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41408. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41409. _this.anisotropicFilteringLevel = 1;
  41410. _this._texture = _this._getFromCache(url, true);
  41411. if (!_this._texture) {
  41412. if (!scene.useDelayedTextureLoading) {
  41413. _this.loadTexture();
  41414. }
  41415. else {
  41416. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41417. }
  41418. }
  41419. return _this;
  41420. }
  41421. /**
  41422. * Returns the texture matrix used in most of the material.
  41423. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41424. */
  41425. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41426. return this._textureMatrix;
  41427. };
  41428. /**
  41429. * Occurs when the file being loaded is a .3dl LUT file.
  41430. */
  41431. ColorGradingTexture.prototype.load3dlTexture = function () {
  41432. var engine = this._engine;
  41433. var texture;
  41434. if (engine.webGLVersion === 1) {
  41435. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41436. }
  41437. else {
  41438. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41439. }
  41440. this._texture = texture;
  41441. var callback = function (text) {
  41442. if (typeof text !== "string") {
  41443. return;
  41444. }
  41445. var data = null;
  41446. var tempData = null;
  41447. var line;
  41448. var lines = text.split('\n');
  41449. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41450. var maxColor = 0;
  41451. for (var i = 0; i < lines.length; i++) {
  41452. line = lines[i];
  41453. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41454. continue;
  41455. if (line.indexOf('#') === 0)
  41456. continue;
  41457. var words = line.split(" ");
  41458. if (size === 0) {
  41459. // Number of space + one
  41460. size = words.length;
  41461. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41462. tempData = new Float32Array(size * size * size * 4);
  41463. continue;
  41464. }
  41465. if (size != 0) {
  41466. var r = Math.max(parseInt(words[0]), 0);
  41467. var g = Math.max(parseInt(words[1]), 0);
  41468. var b = Math.max(parseInt(words[2]), 0);
  41469. maxColor = Math.max(r, maxColor);
  41470. maxColor = Math.max(g, maxColor);
  41471. maxColor = Math.max(b, maxColor);
  41472. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41473. if (tempData) {
  41474. tempData[pixelStorageIndex + 0] = r;
  41475. tempData[pixelStorageIndex + 1] = g;
  41476. tempData[pixelStorageIndex + 2] = b;
  41477. }
  41478. pixelIndexSlice++;
  41479. if (pixelIndexSlice % size == 0) {
  41480. pixelIndexH++;
  41481. pixelIndexSlice = 0;
  41482. if (pixelIndexH % size == 0) {
  41483. pixelIndexW++;
  41484. pixelIndexH = 0;
  41485. }
  41486. }
  41487. }
  41488. }
  41489. if (tempData && data) {
  41490. for (var i = 0; i < tempData.length; i++) {
  41491. if (i > 0 && (i + 1) % 4 === 0) {
  41492. data[i] = 255;
  41493. }
  41494. else {
  41495. var value = tempData[i];
  41496. data[i] = (value / maxColor * 255);
  41497. }
  41498. }
  41499. }
  41500. if (texture.is3D) {
  41501. texture.updateSize(size, size, size);
  41502. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41503. }
  41504. else {
  41505. texture.updateSize(size * size, size);
  41506. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41507. }
  41508. };
  41509. var scene = this.getScene();
  41510. if (scene) {
  41511. scene._loadFile(this.url, callback);
  41512. }
  41513. else {
  41514. this._engine._loadFile(this.url, callback);
  41515. }
  41516. return this._texture;
  41517. };
  41518. /**
  41519. * Starts the loading process of the texture.
  41520. */
  41521. ColorGradingTexture.prototype.loadTexture = function () {
  41522. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41523. this.load3dlTexture();
  41524. }
  41525. };
  41526. /**
  41527. * Clones the color gradind texture.
  41528. */
  41529. ColorGradingTexture.prototype.clone = function () {
  41530. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41531. // Base texture
  41532. newTexture.level = this.level;
  41533. return newTexture;
  41534. };
  41535. /**
  41536. * Called during delayed load for textures.
  41537. */
  41538. ColorGradingTexture.prototype.delayLoad = function () {
  41539. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41540. return;
  41541. }
  41542. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41543. this._texture = this._getFromCache(this.url, true);
  41544. if (!this._texture) {
  41545. this.loadTexture();
  41546. }
  41547. };
  41548. /**
  41549. * Parses a color grading texture serialized by Babylon.
  41550. * @param parsedTexture The texture information being parsedTexture
  41551. * @param scene The scene to load the texture in
  41552. * @param rootUrl The root url of the data assets to load
  41553. * @return A color gradind texture
  41554. */
  41555. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41556. var texture = null;
  41557. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41558. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41559. texture.name = parsedTexture.name;
  41560. texture.level = parsedTexture.level;
  41561. }
  41562. return texture;
  41563. };
  41564. /**
  41565. * Serializes the LUT texture to json format.
  41566. */
  41567. ColorGradingTexture.prototype.serialize = function () {
  41568. if (!this.name) {
  41569. return null;
  41570. }
  41571. var serializationObject = {};
  41572. serializationObject.name = this.name;
  41573. serializationObject.level = this.level;
  41574. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41575. return serializationObject;
  41576. };
  41577. /**
  41578. * Empty line regex stored for GC.
  41579. */
  41580. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41581. return ColorGradingTexture;
  41582. }(BABYLON.BaseTexture));
  41583. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41584. })(BABYLON || (BABYLON = {}));
  41585. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41586. var BABYLON;
  41587. (function (BABYLON) {
  41588. /**
  41589. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41590. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41591. * 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;
  41592. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41593. */
  41594. var ColorCurves = /** @class */ (function () {
  41595. function ColorCurves() {
  41596. this._dirty = true;
  41597. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41598. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41599. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41600. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41601. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41602. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41603. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41604. this._globalHue = 30;
  41605. this._globalDensity = 0;
  41606. this._globalSaturation = 0;
  41607. this._globalExposure = 0;
  41608. this._highlightsHue = 30;
  41609. this._highlightsDensity = 0;
  41610. this._highlightsSaturation = 0;
  41611. this._highlightsExposure = 0;
  41612. this._midtonesHue = 30;
  41613. this._midtonesDensity = 0;
  41614. this._midtonesSaturation = 0;
  41615. this._midtonesExposure = 0;
  41616. this._shadowsHue = 30;
  41617. this._shadowsDensity = 0;
  41618. this._shadowsSaturation = 0;
  41619. this._shadowsExposure = 0;
  41620. }
  41621. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41622. /**
  41623. * Gets the global Hue value.
  41624. * 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).
  41625. */
  41626. get: function () {
  41627. return this._globalHue;
  41628. },
  41629. /**
  41630. * Sets the global Hue value.
  41631. * 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).
  41632. */
  41633. set: function (value) {
  41634. this._globalHue = value;
  41635. this._dirty = true;
  41636. },
  41637. enumerable: true,
  41638. configurable: true
  41639. });
  41640. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41641. /**
  41642. * Gets the global Density value.
  41643. * 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.
  41644. * Values less than zero provide a filter of opposite hue.
  41645. */
  41646. get: function () {
  41647. return this._globalDensity;
  41648. },
  41649. /**
  41650. * Sets the global Density value.
  41651. * 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.
  41652. * Values less than zero provide a filter of opposite hue.
  41653. */
  41654. set: function (value) {
  41655. this._globalDensity = value;
  41656. this._dirty = true;
  41657. },
  41658. enumerable: true,
  41659. configurable: true
  41660. });
  41661. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41662. /**
  41663. * Gets the global Saturation value.
  41664. * 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.
  41665. */
  41666. get: function () {
  41667. return this._globalSaturation;
  41668. },
  41669. /**
  41670. * Sets the global Saturation value.
  41671. * 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.
  41672. */
  41673. set: function (value) {
  41674. this._globalSaturation = value;
  41675. this._dirty = true;
  41676. },
  41677. enumerable: true,
  41678. configurable: true
  41679. });
  41680. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41681. /**
  41682. * Gets the highlights Hue value.
  41683. * 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).
  41684. */
  41685. get: function () {
  41686. return this._highlightsHue;
  41687. },
  41688. /**
  41689. * Sets the highlights Hue value.
  41690. * 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).
  41691. */
  41692. set: function (value) {
  41693. this._highlightsHue = value;
  41694. this._dirty = true;
  41695. },
  41696. enumerable: true,
  41697. configurable: true
  41698. });
  41699. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41700. /**
  41701. * Gets the highlights Density value.
  41702. * 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.
  41703. * Values less than zero provide a filter of opposite hue.
  41704. */
  41705. get: function () {
  41706. return this._highlightsDensity;
  41707. },
  41708. /**
  41709. * Sets the highlights Density value.
  41710. * 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.
  41711. * Values less than zero provide a filter of opposite hue.
  41712. */
  41713. set: function (value) {
  41714. this._highlightsDensity = value;
  41715. this._dirty = true;
  41716. },
  41717. enumerable: true,
  41718. configurable: true
  41719. });
  41720. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41721. /**
  41722. * Gets the highlights Saturation value.
  41723. * 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.
  41724. */
  41725. get: function () {
  41726. return this._highlightsSaturation;
  41727. },
  41728. /**
  41729. * Sets the highlights Saturation value.
  41730. * 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.
  41731. */
  41732. set: function (value) {
  41733. this._highlightsSaturation = value;
  41734. this._dirty = true;
  41735. },
  41736. enumerable: true,
  41737. configurable: true
  41738. });
  41739. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41740. /**
  41741. * Gets the highlights Exposure value.
  41742. * 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.
  41743. */
  41744. get: function () {
  41745. return this._highlightsExposure;
  41746. },
  41747. /**
  41748. * Sets the highlights Exposure value.
  41749. * 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.
  41750. */
  41751. set: function (value) {
  41752. this._highlightsExposure = value;
  41753. this._dirty = true;
  41754. },
  41755. enumerable: true,
  41756. configurable: true
  41757. });
  41758. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41759. /**
  41760. * Gets the midtones Hue value.
  41761. * 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).
  41762. */
  41763. get: function () {
  41764. return this._midtonesHue;
  41765. },
  41766. /**
  41767. * Sets the midtones Hue value.
  41768. * 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).
  41769. */
  41770. set: function (value) {
  41771. this._midtonesHue = value;
  41772. this._dirty = true;
  41773. },
  41774. enumerable: true,
  41775. configurable: true
  41776. });
  41777. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41778. /**
  41779. * Gets the midtones Density value.
  41780. * 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.
  41781. * Values less than zero provide a filter of opposite hue.
  41782. */
  41783. get: function () {
  41784. return this._midtonesDensity;
  41785. },
  41786. /**
  41787. * Sets the midtones Density value.
  41788. * 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.
  41789. * Values less than zero provide a filter of opposite hue.
  41790. */
  41791. set: function (value) {
  41792. this._midtonesDensity = value;
  41793. this._dirty = true;
  41794. },
  41795. enumerable: true,
  41796. configurable: true
  41797. });
  41798. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41799. /**
  41800. * Gets the midtones Saturation value.
  41801. * 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.
  41802. */
  41803. get: function () {
  41804. return this._midtonesSaturation;
  41805. },
  41806. /**
  41807. * Sets the midtones Saturation value.
  41808. * 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.
  41809. */
  41810. set: function (value) {
  41811. this._midtonesSaturation = value;
  41812. this._dirty = true;
  41813. },
  41814. enumerable: true,
  41815. configurable: true
  41816. });
  41817. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41818. /**
  41819. * Gets the midtones Exposure value.
  41820. * 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.
  41821. */
  41822. get: function () {
  41823. return this._midtonesExposure;
  41824. },
  41825. /**
  41826. * Sets the midtones Exposure value.
  41827. * 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.
  41828. */
  41829. set: function (value) {
  41830. this._midtonesExposure = value;
  41831. this._dirty = true;
  41832. },
  41833. enumerable: true,
  41834. configurable: true
  41835. });
  41836. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41837. /**
  41838. * Gets the shadows Hue value.
  41839. * 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).
  41840. */
  41841. get: function () {
  41842. return this._shadowsHue;
  41843. },
  41844. /**
  41845. * Sets the shadows Hue value.
  41846. * 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).
  41847. */
  41848. set: function (value) {
  41849. this._shadowsHue = value;
  41850. this._dirty = true;
  41851. },
  41852. enumerable: true,
  41853. configurable: true
  41854. });
  41855. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41856. /**
  41857. * Gets the shadows Density value.
  41858. * 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.
  41859. * Values less than zero provide a filter of opposite hue.
  41860. */
  41861. get: function () {
  41862. return this._shadowsDensity;
  41863. },
  41864. /**
  41865. * Sets the shadows Density value.
  41866. * 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.
  41867. * Values less than zero provide a filter of opposite hue.
  41868. */
  41869. set: function (value) {
  41870. this._shadowsDensity = value;
  41871. this._dirty = true;
  41872. },
  41873. enumerable: true,
  41874. configurable: true
  41875. });
  41876. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41877. /**
  41878. * Gets the shadows Saturation value.
  41879. * 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.
  41880. */
  41881. get: function () {
  41882. return this._shadowsSaturation;
  41883. },
  41884. /**
  41885. * Sets the shadows Saturation value.
  41886. * 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.
  41887. */
  41888. set: function (value) {
  41889. this._shadowsSaturation = value;
  41890. this._dirty = true;
  41891. },
  41892. enumerable: true,
  41893. configurable: true
  41894. });
  41895. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41896. /**
  41897. * Gets the shadows Exposure value.
  41898. * 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.
  41899. */
  41900. get: function () {
  41901. return this._shadowsExposure;
  41902. },
  41903. /**
  41904. * Sets the shadows Exposure value.
  41905. * 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.
  41906. */
  41907. set: function (value) {
  41908. this._shadowsExposure = value;
  41909. this._dirty = true;
  41910. },
  41911. enumerable: true,
  41912. configurable: true
  41913. });
  41914. ColorCurves.prototype.getClassName = function () {
  41915. return "ColorCurves";
  41916. };
  41917. /**
  41918. * Binds the color curves to the shader.
  41919. * @param colorCurves The color curve to bind
  41920. * @param effect The effect to bind to
  41921. */
  41922. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41923. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41924. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41925. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41926. if (colorCurves._dirty) {
  41927. colorCurves._dirty = false;
  41928. // Fill in global info.
  41929. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41930. // Compute highlights info.
  41931. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41932. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41933. // Compute midtones info.
  41934. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41935. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41936. // Compute shadows info.
  41937. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41938. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41939. // Compute deltas (neutral is midtones).
  41940. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41941. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41942. }
  41943. if (effect) {
  41944. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41945. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41946. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41947. }
  41948. };
  41949. /**
  41950. * Prepare the list of uniforms associated with the ColorCurves effects.
  41951. * @param uniformsList The list of uniforms used in the effect
  41952. */
  41953. ColorCurves.PrepareUniforms = function (uniformsList) {
  41954. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41955. };
  41956. /**
  41957. * Returns color grading data based on a hue, density, saturation and exposure value.
  41958. * @param filterHue The hue of the color filter.
  41959. * @param filterDensity The density of the color filter.
  41960. * @param saturation The saturation.
  41961. * @param exposure The exposure.
  41962. * @param result The result data container.
  41963. */
  41964. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41965. if (hue == null) {
  41966. return;
  41967. }
  41968. hue = ColorCurves.clamp(hue, 0, 360);
  41969. density = ColorCurves.clamp(density, -100, 100);
  41970. saturation = ColorCurves.clamp(saturation, -100, 100);
  41971. exposure = ColorCurves.clamp(exposure, -100, 100);
  41972. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41973. // so that the maximum filter density is only 50% control. This provides fine control
  41974. // for small values and reasonable range.
  41975. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41976. density *= 0.5;
  41977. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41978. if (density < 0) {
  41979. density *= -1;
  41980. hue = (hue + 180) % 360;
  41981. }
  41982. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41983. result.scaleToRef(2, result);
  41984. result.a = 1 + 0.01 * saturation;
  41985. };
  41986. /**
  41987. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41988. * @param value The input slider value in range [-100,100].
  41989. * @returns Adjusted value.
  41990. */
  41991. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41992. value /= 100;
  41993. var x = Math.abs(value);
  41994. x = Math.pow(x, 2);
  41995. if (value < 0) {
  41996. x *= -1;
  41997. }
  41998. x *= 100;
  41999. return x;
  42000. };
  42001. /**
  42002. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42003. * @param hue The hue (H) input.
  42004. * @param saturation The saturation (S) input.
  42005. * @param brightness The brightness (B) input.
  42006. * @result An RGBA color represented as Vector4.
  42007. */
  42008. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42009. var h = ColorCurves.clamp(hue, 0, 360);
  42010. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42011. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42012. if (s === 0) {
  42013. result.r = v;
  42014. result.g = v;
  42015. result.b = v;
  42016. }
  42017. else {
  42018. // sector 0 to 5
  42019. h /= 60;
  42020. var i = Math.floor(h);
  42021. // fractional part of h
  42022. var f = h - i;
  42023. var p = v * (1 - s);
  42024. var q = v * (1 - s * f);
  42025. var t = v * (1 - s * (1 - f));
  42026. switch (i) {
  42027. case 0:
  42028. result.r = v;
  42029. result.g = t;
  42030. result.b = p;
  42031. break;
  42032. case 1:
  42033. result.r = q;
  42034. result.g = v;
  42035. result.b = p;
  42036. break;
  42037. case 2:
  42038. result.r = p;
  42039. result.g = v;
  42040. result.b = t;
  42041. break;
  42042. case 3:
  42043. result.r = p;
  42044. result.g = q;
  42045. result.b = v;
  42046. break;
  42047. case 4:
  42048. result.r = t;
  42049. result.g = p;
  42050. result.b = v;
  42051. break;
  42052. default: // case 5:
  42053. result.r = v;
  42054. result.g = p;
  42055. result.b = q;
  42056. break;
  42057. }
  42058. }
  42059. result.a = 1;
  42060. };
  42061. /**
  42062. * Returns a value clamped between min and max
  42063. * @param value The value to clamp
  42064. * @param min The minimum of value
  42065. * @param max The maximum of value
  42066. * @returns The clamped value.
  42067. */
  42068. ColorCurves.clamp = function (value, min, max) {
  42069. return Math.min(Math.max(value, min), max);
  42070. };
  42071. /**
  42072. * Clones the current color curve instance.
  42073. * @return The cloned curves
  42074. */
  42075. ColorCurves.prototype.clone = function () {
  42076. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42077. };
  42078. /**
  42079. * Serializes the current color curve instance to a json representation.
  42080. * @return a JSON representation
  42081. */
  42082. ColorCurves.prototype.serialize = function () {
  42083. return BABYLON.SerializationHelper.Serialize(this);
  42084. };
  42085. /**
  42086. * Parses the color curve from a json representation.
  42087. * @param source the JSON source to parse
  42088. * @return The parsed curves
  42089. */
  42090. ColorCurves.Parse = function (source) {
  42091. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42092. };
  42093. __decorate([
  42094. BABYLON.serialize()
  42095. ], ColorCurves.prototype, "_globalHue", void 0);
  42096. __decorate([
  42097. BABYLON.serialize()
  42098. ], ColorCurves.prototype, "_globalDensity", void 0);
  42099. __decorate([
  42100. BABYLON.serialize()
  42101. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42102. __decorate([
  42103. BABYLON.serialize()
  42104. ], ColorCurves.prototype, "_globalExposure", void 0);
  42105. __decorate([
  42106. BABYLON.serialize()
  42107. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42108. __decorate([
  42109. BABYLON.serialize()
  42110. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42111. __decorate([
  42112. BABYLON.serialize()
  42113. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42114. __decorate([
  42115. BABYLON.serialize()
  42116. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42117. __decorate([
  42118. BABYLON.serialize()
  42119. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42120. __decorate([
  42121. BABYLON.serialize()
  42122. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42123. __decorate([
  42124. BABYLON.serialize()
  42125. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42126. __decorate([
  42127. BABYLON.serialize()
  42128. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42129. return ColorCurves;
  42130. }());
  42131. BABYLON.ColorCurves = ColorCurves;
  42132. })(BABYLON || (BABYLON = {}));
  42133. //# sourceMappingURL=babylon.colorCurves.js.map
  42134. //# sourceMappingURL=babylon.behavior.js.map
  42135. var BABYLON;
  42136. (function (BABYLON) {
  42137. /**
  42138. * "Static Class" containing the most commonly used helper while dealing with material for
  42139. * rendering purpose.
  42140. *
  42141. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42142. *
  42143. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42144. */
  42145. var MaterialHelper = /** @class */ (function () {
  42146. function MaterialHelper() {
  42147. }
  42148. /**
  42149. * Bind the current view position to an effect.
  42150. * @param effect The effect to be bound
  42151. * @param scene The scene the eyes position is used from
  42152. */
  42153. MaterialHelper.BindEyePosition = function (effect, scene) {
  42154. if (scene._forcedViewPosition) {
  42155. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42156. return;
  42157. }
  42158. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42159. };
  42160. /**
  42161. * Helps preparing the defines values about the UVs in used in the effect.
  42162. * UVs are shared as much as we can accross chanels in the shaders.
  42163. * @param texture The texture we are preparing the UVs for
  42164. * @param defines The defines to update
  42165. * @param key The chanel key "diffuse", "specular"... used in the shader
  42166. */
  42167. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42168. defines._needUVs = true;
  42169. defines[key] = true;
  42170. if (texture.getTextureMatrix().isIdentity(true)) {
  42171. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42172. if (texture.coordinatesIndex === 0) {
  42173. defines["MAINUV1"] = true;
  42174. }
  42175. else {
  42176. defines["MAINUV2"] = true;
  42177. }
  42178. }
  42179. else {
  42180. defines[key + "DIRECTUV"] = 0;
  42181. }
  42182. };
  42183. /**
  42184. * Binds a texture matrix value to its corrsponding uniform
  42185. * @param texture The texture to bind the matrix for
  42186. * @param uniformBuffer The uniform buffer receivin the data
  42187. * @param key The chanel key "diffuse", "specular"... used in the shader
  42188. */
  42189. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42190. var matrix = texture.getTextureMatrix();
  42191. if (!matrix.isIdentity(true)) {
  42192. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42193. }
  42194. };
  42195. /**
  42196. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42197. * @param mesh defines the current mesh
  42198. * @param scene defines the current scene
  42199. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42200. * @param pointsCloud defines if point cloud rendering has to be turned on
  42201. * @param fogEnabled defines if fog has to be turned on
  42202. * @param alphaTest defines if alpha testing has to be turned on
  42203. * @param defines defines the current list of defines
  42204. */
  42205. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42206. if (defines._areMiscDirty) {
  42207. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42208. defines["POINTSIZE"] = pointsCloud;
  42209. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42210. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42211. defines["ALPHATEST"] = alphaTest;
  42212. }
  42213. };
  42214. /**
  42215. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42216. * @param scene defines the current scene
  42217. * @param engine defines the current engine
  42218. * @param defines specifies the list of active defines
  42219. * @param useInstances defines if instances have to be turned on
  42220. * @param useClipPlane defines if clip plane have to be turned on
  42221. */
  42222. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42223. if (useClipPlane === void 0) { useClipPlane = null; }
  42224. var changed = false;
  42225. if (useClipPlane == null) {
  42226. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42227. }
  42228. if (defines["CLIPPLANE"] !== useClipPlane) {
  42229. defines["CLIPPLANE"] = useClipPlane;
  42230. changed = true;
  42231. }
  42232. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42233. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42234. changed = true;
  42235. }
  42236. if (defines["INSTANCES"] !== useInstances) {
  42237. defines["INSTANCES"] = useInstances;
  42238. changed = true;
  42239. }
  42240. if (changed) {
  42241. defines.markAsUnprocessed();
  42242. }
  42243. };
  42244. /**
  42245. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42246. * @param mesh The mesh containing the geometry data we will draw
  42247. * @param defines The defines to update
  42248. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42249. * @param useBones Precise whether bones should be used or not (override mesh info)
  42250. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42251. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42252. * @returns false if defines are considered not dirty and have not been checked
  42253. */
  42254. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42255. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42256. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42257. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42258. return false;
  42259. }
  42260. defines._normals = defines._needNormals;
  42261. defines._uvs = defines._needUVs;
  42262. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42263. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42264. defines["TANGENT"] = true;
  42265. }
  42266. if (defines._needUVs) {
  42267. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42268. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42269. }
  42270. else {
  42271. defines["UV1"] = false;
  42272. defines["UV2"] = false;
  42273. }
  42274. if (useVertexColor) {
  42275. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42276. defines["VERTEXCOLOR"] = hasVertexColors;
  42277. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42278. }
  42279. if (useBones) {
  42280. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42281. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42282. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42283. }
  42284. else {
  42285. defines["NUM_BONE_INFLUENCERS"] = 0;
  42286. defines["BonesPerMesh"] = 0;
  42287. }
  42288. }
  42289. if (useMorphTargets) {
  42290. var manager = mesh.morphTargetManager;
  42291. if (manager) {
  42292. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42293. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42294. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42295. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42296. }
  42297. else {
  42298. defines["MORPHTARGETS_TANGENT"] = false;
  42299. defines["MORPHTARGETS_NORMAL"] = false;
  42300. defines["MORPHTARGETS"] = false;
  42301. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42302. }
  42303. }
  42304. return true;
  42305. };
  42306. /**
  42307. * Prepares the defines related to the light information passed in parameter
  42308. * @param scene The scene we are intending to draw
  42309. * @param mesh The mesh the effect is compiling for
  42310. * @param defines The defines to update
  42311. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42312. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42313. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42314. * @returns true if normals will be required for the rest of the effect
  42315. */
  42316. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42317. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42318. if (disableLighting === void 0) { disableLighting = false; }
  42319. if (!defines._areLightsDirty) {
  42320. return defines._needNormals;
  42321. }
  42322. var lightIndex = 0;
  42323. var needNormals = false;
  42324. var needRebuild = false;
  42325. var lightmapMode = false;
  42326. var shadowEnabled = false;
  42327. var specularEnabled = false;
  42328. if (scene.lightsEnabled && !disableLighting) {
  42329. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42330. var light = _a[_i];
  42331. needNormals = true;
  42332. if (defines["LIGHT" + lightIndex] === undefined) {
  42333. needRebuild = true;
  42334. }
  42335. defines["LIGHT" + lightIndex] = true;
  42336. defines["SPOTLIGHT" + lightIndex] = false;
  42337. defines["HEMILIGHT" + lightIndex] = false;
  42338. defines["POINTLIGHT" + lightIndex] = false;
  42339. defines["DIRLIGHT" + lightIndex] = false;
  42340. var type;
  42341. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42342. type = "SPOTLIGHT" + lightIndex;
  42343. var spotLight = light;
  42344. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42345. }
  42346. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42347. type = "HEMILIGHT" + lightIndex;
  42348. }
  42349. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42350. type = "POINTLIGHT" + lightIndex;
  42351. }
  42352. else {
  42353. type = "DIRLIGHT" + lightIndex;
  42354. }
  42355. defines[type] = true;
  42356. // Specular
  42357. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42358. specularEnabled = true;
  42359. }
  42360. // Shadows
  42361. defines["SHADOW" + lightIndex] = false;
  42362. defines["SHADOWPCF" + lightIndex] = false;
  42363. defines["SHADOWPCSS" + lightIndex] = false;
  42364. defines["SHADOWPOISSON" + lightIndex] = false;
  42365. defines["SHADOWESM" + lightIndex] = false;
  42366. defines["SHADOWCUBE" + lightIndex] = false;
  42367. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42368. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42369. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42370. var shadowGenerator = light.getShadowGenerator();
  42371. if (shadowGenerator) {
  42372. shadowEnabled = true;
  42373. shadowGenerator.prepareDefines(defines, lightIndex);
  42374. }
  42375. }
  42376. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42377. lightmapMode = true;
  42378. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42379. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42380. }
  42381. else {
  42382. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42383. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42384. }
  42385. lightIndex++;
  42386. if (lightIndex === maxSimultaneousLights)
  42387. break;
  42388. }
  42389. }
  42390. defines["SPECULARTERM"] = specularEnabled;
  42391. defines["SHADOWS"] = shadowEnabled;
  42392. // Resetting all other lights if any
  42393. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42394. if (defines["LIGHT" + index] !== undefined) {
  42395. defines["LIGHT" + index] = false;
  42396. defines["HEMILIGHT" + lightIndex] = false;
  42397. defines["POINTLIGHT" + lightIndex] = false;
  42398. defines["DIRLIGHT" + lightIndex] = false;
  42399. defines["SPOTLIGHT" + lightIndex] = false;
  42400. defines["SHADOW" + lightIndex] = false;
  42401. }
  42402. }
  42403. var caps = scene.getEngine().getCaps();
  42404. if (defines["SHADOWFLOAT"] === undefined) {
  42405. needRebuild = true;
  42406. }
  42407. defines["SHADOWFLOAT"] = shadowEnabled &&
  42408. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42409. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42410. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42411. if (needRebuild) {
  42412. defines.rebuild();
  42413. }
  42414. return needNormals;
  42415. };
  42416. /**
  42417. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42418. * that won t be acctive due to defines being turned off.
  42419. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42420. * @param samplersList The samplers list
  42421. * @param defines The defines helping in the list generation
  42422. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42423. */
  42424. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42425. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42426. var uniformsList;
  42427. var uniformBuffersList = null;
  42428. if (uniformsListOrOptions.uniformsNames) {
  42429. var options = uniformsListOrOptions;
  42430. uniformsList = options.uniformsNames;
  42431. uniformBuffersList = options.uniformBuffersNames;
  42432. samplersList = options.samplers;
  42433. defines = options.defines;
  42434. maxSimultaneousLights = options.maxSimultaneousLights;
  42435. }
  42436. else {
  42437. uniformsList = uniformsListOrOptions;
  42438. if (!samplersList) {
  42439. samplersList = [];
  42440. }
  42441. }
  42442. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42443. if (!defines["LIGHT" + lightIndex]) {
  42444. break;
  42445. }
  42446. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42447. if (uniformBuffersList) {
  42448. uniformBuffersList.push("Light" + lightIndex);
  42449. }
  42450. samplersList.push("shadowSampler" + lightIndex);
  42451. samplersList.push("depthSampler" + lightIndex);
  42452. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42453. samplersList.push("projectionLightSampler" + lightIndex);
  42454. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42455. }
  42456. }
  42457. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42458. uniformsList.push("morphTargetInfluences");
  42459. }
  42460. };
  42461. /**
  42462. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42463. * @param defines The defines to update while falling back
  42464. * @param fallbacks The authorized effect fallbacks
  42465. * @param maxSimultaneousLights The maximum number of lights allowed
  42466. * @param rank the current rank of the Effect
  42467. * @returns The newly affected rank
  42468. */
  42469. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42470. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42471. if (rank === void 0) { rank = 0; }
  42472. var lightFallbackRank = 0;
  42473. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42474. if (!defines["LIGHT" + lightIndex]) {
  42475. break;
  42476. }
  42477. if (lightIndex > 0) {
  42478. lightFallbackRank = rank + lightIndex;
  42479. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42480. }
  42481. if (!defines["SHADOWS"]) {
  42482. if (defines["SHADOW" + lightIndex]) {
  42483. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42484. }
  42485. if (defines["SHADOWPCF" + lightIndex]) {
  42486. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42487. }
  42488. if (defines["SHADOWPCSS" + lightIndex]) {
  42489. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42490. }
  42491. if (defines["SHADOWPOISSON" + lightIndex]) {
  42492. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42493. }
  42494. if (defines["SHADOWESM" + lightIndex]) {
  42495. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42496. }
  42497. }
  42498. }
  42499. return lightFallbackRank++;
  42500. };
  42501. /**
  42502. * Prepares the list of attributes required for morph targets according to the effect defines.
  42503. * @param attribs The current list of supported attribs
  42504. * @param mesh The mesh to prepare the morph targets attributes for
  42505. * @param defines The current Defines of the effect
  42506. */
  42507. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42508. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42509. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42510. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42511. var manager = mesh.morphTargetManager;
  42512. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42513. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42514. for (var index = 0; index < influencers; index++) {
  42515. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42516. if (normal) {
  42517. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42518. }
  42519. if (tangent) {
  42520. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42521. }
  42522. if (attribs.length > maxAttributesCount) {
  42523. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42524. }
  42525. }
  42526. }
  42527. };
  42528. /**
  42529. * Prepares the list of attributes required for bones according to the effect defines.
  42530. * @param attribs The current list of supported attribs
  42531. * @param mesh The mesh to prepare the bones attributes for
  42532. * @param defines The current Defines of the effect
  42533. * @param fallbacks The current efffect fallback strategy
  42534. */
  42535. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42536. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42537. fallbacks.addCPUSkinningFallback(0, mesh);
  42538. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42539. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42540. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42541. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42542. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42543. }
  42544. }
  42545. };
  42546. /**
  42547. * Prepares the list of attributes required for instances according to the effect defines.
  42548. * @param attribs The current list of supported attribs
  42549. * @param defines The current Defines of the effect
  42550. */
  42551. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42552. if (defines["INSTANCES"]) {
  42553. attribs.push("world0");
  42554. attribs.push("world1");
  42555. attribs.push("world2");
  42556. attribs.push("world3");
  42557. }
  42558. };
  42559. /**
  42560. * Binds the light shadow information to the effect for the given mesh.
  42561. * @param light The light containing the generator
  42562. * @param scene The scene the lights belongs to
  42563. * @param mesh The mesh we are binding the information to render
  42564. * @param lightIndex The light index in the effect used to render the mesh
  42565. * @param effect The effect we are binding the data to
  42566. */
  42567. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42568. if (light.shadowEnabled && mesh.receiveShadows) {
  42569. var shadowGenerator = light.getShadowGenerator();
  42570. if (shadowGenerator) {
  42571. shadowGenerator.bindShadowLight(lightIndex, effect);
  42572. }
  42573. }
  42574. };
  42575. /**
  42576. * Binds the light information to the effect.
  42577. * @param light The light containing the generator
  42578. * @param effect The effect we are binding the data to
  42579. * @param lightIndex The light index in the effect used to render
  42580. */
  42581. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42582. light.transferToEffect(effect, lightIndex + "");
  42583. };
  42584. /**
  42585. * Binds the lights information from the scene to the effect for the given mesh.
  42586. * @param scene The scene the lights belongs to
  42587. * @param mesh The mesh we are binding the information to render
  42588. * @param effect The effect we are binding the data to
  42589. * @param defines The generated defines for the effect
  42590. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42591. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42592. */
  42593. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42594. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42595. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42596. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42597. for (var i = 0; i < len; i++) {
  42598. var light = mesh._lightSources[i];
  42599. var iAsString = i.toString();
  42600. var scaledIntensity = light.getScaledIntensity();
  42601. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42602. MaterialHelper.BindLightProperties(light, effect, i);
  42603. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42604. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42605. if (defines["SPECULARTERM"]) {
  42606. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42607. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42608. }
  42609. // Shadows
  42610. if (scene.shadowsEnabled) {
  42611. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42612. }
  42613. light._uniformBuffer.update();
  42614. }
  42615. };
  42616. /**
  42617. * Binds the fog information from the scene to the effect for the given mesh.
  42618. * @param scene The scene the lights belongs to
  42619. * @param mesh The mesh we are binding the information to render
  42620. * @param effect The effect we are binding the data to
  42621. */
  42622. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42623. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42624. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42625. effect.setColor3("vFogColor", scene.fogColor);
  42626. }
  42627. };
  42628. /**
  42629. * Binds the bones information from the mesh to the effect.
  42630. * @param mesh The mesh we are binding the information to render
  42631. * @param effect The effect we are binding the data to
  42632. */
  42633. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42634. if (!effect || !mesh) {
  42635. return;
  42636. }
  42637. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42638. mesh.computeBonesUsingShaders = false;
  42639. }
  42640. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42641. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42642. if (matrices) {
  42643. effect.setMatrices("mBones", matrices);
  42644. }
  42645. }
  42646. };
  42647. /**
  42648. * Binds the morph targets information from the mesh to the effect.
  42649. * @param abstractMesh The mesh we are binding the information to render
  42650. * @param effect The effect we are binding the data to
  42651. */
  42652. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42653. var manager = abstractMesh.morphTargetManager;
  42654. if (!abstractMesh || !manager) {
  42655. return;
  42656. }
  42657. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42658. };
  42659. /**
  42660. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42661. * @param defines The generated defines used in the effect
  42662. * @param effect The effect we are binding the data to
  42663. * @param scene The scene we are willing to render with logarithmic scale for
  42664. */
  42665. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42666. if (defines["LOGARITHMICDEPTH"]) {
  42667. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42668. }
  42669. };
  42670. /**
  42671. * Binds the clip plane information from the scene to the effect.
  42672. * @param scene The scene the clip plane information are extracted from
  42673. * @param effect The effect we are binding the data to
  42674. */
  42675. MaterialHelper.BindClipPlane = function (effect, scene) {
  42676. if (scene.clipPlane) {
  42677. var clipPlane = scene.clipPlane;
  42678. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42679. }
  42680. };
  42681. return MaterialHelper;
  42682. }());
  42683. BABYLON.MaterialHelper = MaterialHelper;
  42684. })(BABYLON || (BABYLON = {}));
  42685. //# sourceMappingURL=babylon.materialHelper.js.map
  42686. var BABYLON;
  42687. (function (BABYLON) {
  42688. var PushMaterial = /** @class */ (function (_super) {
  42689. __extends(PushMaterial, _super);
  42690. function PushMaterial(name, scene) {
  42691. var _this = _super.call(this, name, scene) || this;
  42692. _this._normalMatrix = new BABYLON.Matrix();
  42693. _this.storeEffectOnSubMeshes = true;
  42694. return _this;
  42695. }
  42696. PushMaterial.prototype.getEffect = function () {
  42697. return this._activeEffect;
  42698. };
  42699. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42700. if (!mesh) {
  42701. return false;
  42702. }
  42703. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42704. return true;
  42705. }
  42706. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42707. };
  42708. /**
  42709. * Binds the given world matrix to the active effect
  42710. *
  42711. * @param world the matrix to bind
  42712. */
  42713. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42714. this._activeEffect.setMatrix("world", world);
  42715. };
  42716. /**
  42717. * Binds the given normal matrix to the active effect
  42718. *
  42719. * @param normalMatrix the matrix to bind
  42720. */
  42721. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42722. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42723. };
  42724. PushMaterial.prototype.bind = function (world, mesh) {
  42725. if (!mesh) {
  42726. return;
  42727. }
  42728. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42729. };
  42730. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42731. if (effect === void 0) { effect = null; }
  42732. _super.prototype._afterBind.call(this, mesh);
  42733. this.getScene()._cachedEffect = effect;
  42734. };
  42735. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42736. if (visibility === void 0) { visibility = 1; }
  42737. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42738. };
  42739. return PushMaterial;
  42740. }(BABYLON.Material));
  42741. BABYLON.PushMaterial = PushMaterial;
  42742. })(BABYLON || (BABYLON = {}));
  42743. //# sourceMappingURL=babylon.pushMaterial.js.map
  42744. var BABYLON;
  42745. (function (BABYLON) {
  42746. /** @hidden */
  42747. var StandardMaterialDefines = /** @class */ (function (_super) {
  42748. __extends(StandardMaterialDefines, _super);
  42749. function StandardMaterialDefines() {
  42750. var _this = _super.call(this) || this;
  42751. _this.MAINUV1 = false;
  42752. _this.MAINUV2 = false;
  42753. _this.DIFFUSE = false;
  42754. _this.DIFFUSEDIRECTUV = 0;
  42755. _this.AMBIENT = false;
  42756. _this.AMBIENTDIRECTUV = 0;
  42757. _this.OPACITY = false;
  42758. _this.OPACITYDIRECTUV = 0;
  42759. _this.OPACITYRGB = false;
  42760. _this.REFLECTION = false;
  42761. _this.EMISSIVE = false;
  42762. _this.EMISSIVEDIRECTUV = 0;
  42763. _this.SPECULAR = false;
  42764. _this.SPECULARDIRECTUV = 0;
  42765. _this.BUMP = false;
  42766. _this.BUMPDIRECTUV = 0;
  42767. _this.PARALLAX = false;
  42768. _this.PARALLAXOCCLUSION = false;
  42769. _this.SPECULAROVERALPHA = false;
  42770. _this.CLIPPLANE = false;
  42771. _this.ALPHATEST = false;
  42772. _this.DEPTHPREPASS = false;
  42773. _this.ALPHAFROMDIFFUSE = false;
  42774. _this.POINTSIZE = false;
  42775. _this.FOG = false;
  42776. _this.SPECULARTERM = false;
  42777. _this.DIFFUSEFRESNEL = false;
  42778. _this.OPACITYFRESNEL = false;
  42779. _this.REFLECTIONFRESNEL = false;
  42780. _this.REFRACTIONFRESNEL = false;
  42781. _this.EMISSIVEFRESNEL = false;
  42782. _this.FRESNEL = false;
  42783. _this.NORMAL = false;
  42784. _this.UV1 = false;
  42785. _this.UV2 = false;
  42786. _this.VERTEXCOLOR = false;
  42787. _this.VERTEXALPHA = false;
  42788. _this.NUM_BONE_INFLUENCERS = 0;
  42789. _this.BonesPerMesh = 0;
  42790. _this.INSTANCES = false;
  42791. _this.GLOSSINESS = false;
  42792. _this.ROUGHNESS = false;
  42793. _this.EMISSIVEASILLUMINATION = false;
  42794. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42795. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42796. _this.LIGHTMAP = false;
  42797. _this.LIGHTMAPDIRECTUV = 0;
  42798. _this.OBJECTSPACE_NORMALMAP = false;
  42799. _this.USELIGHTMAPASSHADOWMAP = false;
  42800. _this.REFLECTIONMAP_3D = false;
  42801. _this.REFLECTIONMAP_SPHERICAL = false;
  42802. _this.REFLECTIONMAP_PLANAR = false;
  42803. _this.REFLECTIONMAP_CUBIC = false;
  42804. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42805. _this.REFLECTIONMAP_PROJECTION = false;
  42806. _this.REFLECTIONMAP_SKYBOX = false;
  42807. _this.REFLECTIONMAP_EXPLICIT = false;
  42808. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42809. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42810. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42811. _this.INVERTCUBICMAP = false;
  42812. _this.LOGARITHMICDEPTH = false;
  42813. _this.REFRACTION = false;
  42814. _this.REFRACTIONMAP_3D = false;
  42815. _this.REFLECTIONOVERALPHA = false;
  42816. _this.TWOSIDEDLIGHTING = false;
  42817. _this.SHADOWFLOAT = false;
  42818. _this.MORPHTARGETS = false;
  42819. _this.MORPHTARGETS_NORMAL = false;
  42820. _this.MORPHTARGETS_TANGENT = false;
  42821. _this.NUM_MORPH_INFLUENCERS = 0;
  42822. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42823. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42824. _this.IMAGEPROCESSING = false;
  42825. _this.VIGNETTE = false;
  42826. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42827. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42828. _this.TONEMAPPING = false;
  42829. _this.CONTRAST = false;
  42830. _this.COLORCURVES = false;
  42831. _this.COLORGRADING = false;
  42832. _this.COLORGRADING3D = false;
  42833. _this.SAMPLER3DGREENDEPTH = false;
  42834. _this.SAMPLER3DBGRMAP = false;
  42835. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42836. /**
  42837. * If the reflection texture on this material is in linear color space
  42838. * @hidden
  42839. */
  42840. _this.IS_REFLECTION_LINEAR = false;
  42841. /**
  42842. * If the refraction texture on this material is in linear color space
  42843. * @hidden
  42844. */
  42845. _this.IS_REFRACTION_LINEAR = false;
  42846. _this.EXPOSURE = false;
  42847. _this.rebuild();
  42848. return _this;
  42849. }
  42850. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42851. var modes = [
  42852. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42853. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42854. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42855. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42856. ];
  42857. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42858. var mode = modes_1[_i];
  42859. this[mode] = (mode === modeToEnable);
  42860. }
  42861. };
  42862. return StandardMaterialDefines;
  42863. }(BABYLON.MaterialDefines));
  42864. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42865. var StandardMaterial = /** @class */ (function (_super) {
  42866. __extends(StandardMaterial, _super);
  42867. function StandardMaterial(name, scene) {
  42868. var _this = _super.call(this, name, scene) || this;
  42869. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42870. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42871. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42872. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42873. _this.specularPower = 64;
  42874. _this._useAlphaFromDiffuseTexture = false;
  42875. _this._useEmissiveAsIllumination = false;
  42876. _this._linkEmissiveWithDiffuse = false;
  42877. _this._useSpecularOverAlpha = false;
  42878. _this._useReflectionOverAlpha = false;
  42879. _this._disableLighting = false;
  42880. _this._useObjectSpaceNormalMap = false;
  42881. _this._useParallax = false;
  42882. _this._useParallaxOcclusion = false;
  42883. _this.parallaxScaleBias = 0.05;
  42884. _this._roughness = 0;
  42885. _this.indexOfRefraction = 0.98;
  42886. _this.invertRefractionY = true;
  42887. /**
  42888. * Defines the alpha limits in alpha test mode
  42889. */
  42890. _this.alphaCutOff = 0.4;
  42891. _this._useLightmapAsShadowmap = false;
  42892. _this._useReflectionFresnelFromSpecular = false;
  42893. _this._useGlossinessFromSpecularMapAlpha = false;
  42894. _this._maxSimultaneousLights = 4;
  42895. /**
  42896. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42897. */
  42898. _this._invertNormalMapX = false;
  42899. /**
  42900. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42901. */
  42902. _this._invertNormalMapY = false;
  42903. /**
  42904. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42905. */
  42906. _this._twoSidedLighting = false;
  42907. _this._renderTargets = new BABYLON.SmartArray(16);
  42908. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42909. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42910. // Setup the default processing configuration to the scene.
  42911. _this._attachImageProcessingConfiguration(null);
  42912. _this.getRenderTargetTextures = function () {
  42913. _this._renderTargets.reset();
  42914. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42915. _this._renderTargets.push(_this._reflectionTexture);
  42916. }
  42917. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42918. _this._renderTargets.push(_this._refractionTexture);
  42919. }
  42920. return _this._renderTargets;
  42921. };
  42922. return _this;
  42923. }
  42924. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42925. /**
  42926. * Gets the image processing configuration used either in this material.
  42927. */
  42928. get: function () {
  42929. return this._imageProcessingConfiguration;
  42930. },
  42931. /**
  42932. * Sets the Default image processing configuration used either in the this material.
  42933. *
  42934. * If sets to null, the scene one is in use.
  42935. */
  42936. set: function (value) {
  42937. this._attachImageProcessingConfiguration(value);
  42938. // Ensure the effect will be rebuilt.
  42939. this._markAllSubMeshesAsTexturesDirty();
  42940. },
  42941. enumerable: true,
  42942. configurable: true
  42943. });
  42944. /**
  42945. * Attaches a new image processing configuration to the Standard Material.
  42946. * @param configuration
  42947. */
  42948. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42949. var _this = this;
  42950. if (configuration === this._imageProcessingConfiguration) {
  42951. return;
  42952. }
  42953. // Detaches observer.
  42954. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42955. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42956. }
  42957. // Pick the scene configuration if needed.
  42958. if (!configuration) {
  42959. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42960. }
  42961. else {
  42962. this._imageProcessingConfiguration = configuration;
  42963. }
  42964. // Attaches observer.
  42965. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42966. _this._markAllSubMeshesAsImageProcessingDirty();
  42967. });
  42968. };
  42969. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42970. /**
  42971. * Gets wether the color curves effect is enabled.
  42972. */
  42973. get: function () {
  42974. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42975. },
  42976. /**
  42977. * Sets wether the color curves effect is enabled.
  42978. */
  42979. set: function (value) {
  42980. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42981. },
  42982. enumerable: true,
  42983. configurable: true
  42984. });
  42985. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42986. /**
  42987. * Gets wether the color grading effect is enabled.
  42988. */
  42989. get: function () {
  42990. return this.imageProcessingConfiguration.colorGradingEnabled;
  42991. },
  42992. /**
  42993. * Gets wether the color grading effect is enabled.
  42994. */
  42995. set: function (value) {
  42996. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42997. },
  42998. enumerable: true,
  42999. configurable: true
  43000. });
  43001. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43002. /**
  43003. * Gets wether tonemapping is enabled or not.
  43004. */
  43005. get: function () {
  43006. return this._imageProcessingConfiguration.toneMappingEnabled;
  43007. },
  43008. /**
  43009. * Sets wether tonemapping is enabled or not
  43010. */
  43011. set: function (value) {
  43012. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43013. },
  43014. enumerable: true,
  43015. configurable: true
  43016. });
  43017. ;
  43018. ;
  43019. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43020. /**
  43021. * The camera exposure used on this material.
  43022. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43023. * This corresponds to a photographic exposure.
  43024. */
  43025. get: function () {
  43026. return this._imageProcessingConfiguration.exposure;
  43027. },
  43028. /**
  43029. * The camera exposure used on this material.
  43030. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43031. * This corresponds to a photographic exposure.
  43032. */
  43033. set: function (value) {
  43034. this._imageProcessingConfiguration.exposure = value;
  43035. },
  43036. enumerable: true,
  43037. configurable: true
  43038. });
  43039. ;
  43040. ;
  43041. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43042. /**
  43043. * Gets The camera contrast used on this material.
  43044. */
  43045. get: function () {
  43046. return this._imageProcessingConfiguration.contrast;
  43047. },
  43048. /**
  43049. * Sets The camera contrast used on this material.
  43050. */
  43051. set: function (value) {
  43052. this._imageProcessingConfiguration.contrast = value;
  43053. },
  43054. enumerable: true,
  43055. configurable: true
  43056. });
  43057. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43058. /**
  43059. * Gets the Color Grading 2D Lookup Texture.
  43060. */
  43061. get: function () {
  43062. return this._imageProcessingConfiguration.colorGradingTexture;
  43063. },
  43064. /**
  43065. * Sets the Color Grading 2D Lookup Texture.
  43066. */
  43067. set: function (value) {
  43068. this._imageProcessingConfiguration.colorGradingTexture = value;
  43069. },
  43070. enumerable: true,
  43071. configurable: true
  43072. });
  43073. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43074. /**
  43075. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43076. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43077. * 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;
  43078. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43079. */
  43080. get: function () {
  43081. return this._imageProcessingConfiguration.colorCurves;
  43082. },
  43083. /**
  43084. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43085. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43086. * 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;
  43087. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43088. */
  43089. set: function (value) {
  43090. this._imageProcessingConfiguration.colorCurves = value;
  43091. },
  43092. enumerable: true,
  43093. configurable: true
  43094. });
  43095. StandardMaterial.prototype.getClassName = function () {
  43096. return "StandardMaterial";
  43097. };
  43098. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43099. get: function () {
  43100. return this._useLogarithmicDepth;
  43101. },
  43102. set: function (value) {
  43103. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43104. this._markAllSubMeshesAsMiscDirty();
  43105. },
  43106. enumerable: true,
  43107. configurable: true
  43108. });
  43109. StandardMaterial.prototype.needAlphaBlending = function () {
  43110. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43111. };
  43112. StandardMaterial.prototype.needAlphaTesting = function () {
  43113. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43114. };
  43115. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43116. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43117. };
  43118. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43119. return this._diffuseTexture;
  43120. };
  43121. /**
  43122. * Child classes can use it to update shaders
  43123. */
  43124. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43125. if (useInstances === void 0) { useInstances = false; }
  43126. if (subMesh.effect && this.isFrozen) {
  43127. if (this._wasPreviouslyReady && subMesh.effect) {
  43128. return true;
  43129. }
  43130. }
  43131. if (!subMesh._materialDefines) {
  43132. subMesh._materialDefines = new StandardMaterialDefines();
  43133. }
  43134. var scene = this.getScene();
  43135. var defines = subMesh._materialDefines;
  43136. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43137. if (defines._renderId === scene.getRenderId()) {
  43138. return true;
  43139. }
  43140. }
  43141. var engine = scene.getEngine();
  43142. // Lights
  43143. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43144. // Textures
  43145. if (defines._areTexturesDirty) {
  43146. defines._needUVs = false;
  43147. defines.MAINUV1 = false;
  43148. defines.MAINUV2 = false;
  43149. if (scene.texturesEnabled) {
  43150. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43151. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43152. return false;
  43153. }
  43154. else {
  43155. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43156. }
  43157. }
  43158. else {
  43159. defines.DIFFUSE = false;
  43160. }
  43161. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43162. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43163. return false;
  43164. }
  43165. else {
  43166. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43167. }
  43168. }
  43169. else {
  43170. defines.AMBIENT = false;
  43171. }
  43172. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43173. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43174. return false;
  43175. }
  43176. else {
  43177. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43178. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43179. }
  43180. }
  43181. else {
  43182. defines.OPACITY = false;
  43183. }
  43184. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43185. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43186. return false;
  43187. }
  43188. else {
  43189. defines._needNormals = true;
  43190. defines.REFLECTION = true;
  43191. defines.ROUGHNESS = (this._roughness > 0);
  43192. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43193. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43194. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43195. switch (this._reflectionTexture.coordinatesMode) {
  43196. case BABYLON.Texture.EXPLICIT_MODE:
  43197. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43198. break;
  43199. case BABYLON.Texture.PLANAR_MODE:
  43200. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43201. break;
  43202. case BABYLON.Texture.PROJECTION_MODE:
  43203. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43204. break;
  43205. case BABYLON.Texture.SKYBOX_MODE:
  43206. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43207. break;
  43208. case BABYLON.Texture.SPHERICAL_MODE:
  43209. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43210. break;
  43211. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43212. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43213. break;
  43214. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43215. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43216. break;
  43217. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43218. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43219. break;
  43220. case BABYLON.Texture.CUBIC_MODE:
  43221. case BABYLON.Texture.INVCUBIC_MODE:
  43222. default:
  43223. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43224. break;
  43225. }
  43226. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43227. }
  43228. }
  43229. else {
  43230. defines.REFLECTION = false;
  43231. }
  43232. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43233. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43234. return false;
  43235. }
  43236. else {
  43237. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43238. }
  43239. }
  43240. else {
  43241. defines.EMISSIVE = false;
  43242. }
  43243. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43244. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43245. return false;
  43246. }
  43247. else {
  43248. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43249. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43250. }
  43251. }
  43252. else {
  43253. defines.LIGHTMAP = false;
  43254. }
  43255. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43256. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43257. return false;
  43258. }
  43259. else {
  43260. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43261. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43262. }
  43263. }
  43264. else {
  43265. defines.SPECULAR = false;
  43266. }
  43267. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43268. // Bump texure can not be not blocking.
  43269. if (!this._bumpTexture.isReady()) {
  43270. return false;
  43271. }
  43272. else {
  43273. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43274. defines.PARALLAX = this._useParallax;
  43275. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43276. }
  43277. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43278. }
  43279. else {
  43280. defines.BUMP = false;
  43281. }
  43282. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43283. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43284. return false;
  43285. }
  43286. else {
  43287. defines._needUVs = true;
  43288. defines.REFRACTION = true;
  43289. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43290. }
  43291. }
  43292. else {
  43293. defines.REFRACTION = false;
  43294. }
  43295. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43296. }
  43297. else {
  43298. defines.DIFFUSE = false;
  43299. defines.AMBIENT = false;
  43300. defines.OPACITY = false;
  43301. defines.REFLECTION = false;
  43302. defines.EMISSIVE = false;
  43303. defines.LIGHTMAP = false;
  43304. defines.BUMP = false;
  43305. defines.REFRACTION = false;
  43306. }
  43307. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43308. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43309. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43310. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43311. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43312. }
  43313. if (defines._areImageProcessingDirty) {
  43314. if (!this._imageProcessingConfiguration.isReady()) {
  43315. return false;
  43316. }
  43317. this._imageProcessingConfiguration.prepareDefines(defines);
  43318. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43319. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43320. }
  43321. if (defines._areFresnelDirty) {
  43322. if (StandardMaterial.FresnelEnabled) {
  43323. // Fresnel
  43324. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43325. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43326. this._reflectionFresnelParameters) {
  43327. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43328. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43329. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43330. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43331. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43332. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43333. defines._needNormals = true;
  43334. defines.FRESNEL = true;
  43335. }
  43336. }
  43337. else {
  43338. defines.FRESNEL = false;
  43339. }
  43340. }
  43341. // Misc.
  43342. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43343. // Attribs
  43344. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43345. // Values that need to be evaluated on every frame
  43346. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43347. // Get correct effect
  43348. if (defines.isDirty) {
  43349. defines.markAsProcessed();
  43350. scene.resetCachedMaterial();
  43351. // Fallbacks
  43352. var fallbacks = new BABYLON.EffectFallbacks();
  43353. if (defines.REFLECTION) {
  43354. fallbacks.addFallback(0, "REFLECTION");
  43355. }
  43356. if (defines.SPECULAR) {
  43357. fallbacks.addFallback(0, "SPECULAR");
  43358. }
  43359. if (defines.BUMP) {
  43360. fallbacks.addFallback(0, "BUMP");
  43361. }
  43362. if (defines.PARALLAX) {
  43363. fallbacks.addFallback(1, "PARALLAX");
  43364. }
  43365. if (defines.PARALLAXOCCLUSION) {
  43366. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43367. }
  43368. if (defines.SPECULAROVERALPHA) {
  43369. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43370. }
  43371. if (defines.FOG) {
  43372. fallbacks.addFallback(1, "FOG");
  43373. }
  43374. if (defines.POINTSIZE) {
  43375. fallbacks.addFallback(0, "POINTSIZE");
  43376. }
  43377. if (defines.LOGARITHMICDEPTH) {
  43378. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43379. }
  43380. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43381. if (defines.SPECULARTERM) {
  43382. fallbacks.addFallback(0, "SPECULARTERM");
  43383. }
  43384. if (defines.DIFFUSEFRESNEL) {
  43385. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43386. }
  43387. if (defines.OPACITYFRESNEL) {
  43388. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43389. }
  43390. if (defines.REFLECTIONFRESNEL) {
  43391. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43392. }
  43393. if (defines.EMISSIVEFRESNEL) {
  43394. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43395. }
  43396. if (defines.FRESNEL) {
  43397. fallbacks.addFallback(4, "FRESNEL");
  43398. }
  43399. //Attributes
  43400. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43401. if (defines.NORMAL) {
  43402. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43403. }
  43404. if (defines.UV1) {
  43405. attribs.push(BABYLON.VertexBuffer.UVKind);
  43406. }
  43407. if (defines.UV2) {
  43408. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43409. }
  43410. if (defines.VERTEXCOLOR) {
  43411. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43412. }
  43413. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43414. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43415. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43416. var shaderName = "default";
  43417. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43418. "vFogInfos", "vFogColor", "pointSize",
  43419. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43420. "mBones",
  43421. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43422. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43423. "vReflectionPosition", "vReflectionSize",
  43424. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43425. ];
  43426. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43427. var uniformBuffers = ["Material", "Scene"];
  43428. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43429. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43430. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43431. uniformsNames: uniforms,
  43432. uniformBuffersNames: uniformBuffers,
  43433. samplers: samplers,
  43434. defines: defines,
  43435. maxSimultaneousLights: this._maxSimultaneousLights
  43436. });
  43437. if (this.customShaderNameResolve) {
  43438. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43439. }
  43440. var join = defines.toString();
  43441. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43442. attributes: attribs,
  43443. uniformsNames: uniforms,
  43444. uniformBuffersNames: uniformBuffers,
  43445. samplers: samplers,
  43446. defines: join,
  43447. fallbacks: fallbacks,
  43448. onCompiled: this.onCompiled,
  43449. onError: this.onError,
  43450. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43451. }, engine), defines);
  43452. this.buildUniformLayout();
  43453. }
  43454. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43455. return false;
  43456. }
  43457. defines._renderId = scene.getRenderId();
  43458. this._wasPreviouslyReady = true;
  43459. return true;
  43460. };
  43461. StandardMaterial.prototype.buildUniformLayout = function () {
  43462. // Order is important !
  43463. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43464. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43465. this._uniformBuffer.addUniform("opacityParts", 4);
  43466. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43467. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43468. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43469. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43470. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43471. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43472. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43473. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43474. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43475. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43476. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43477. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43478. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43479. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43480. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43481. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43482. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43483. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43484. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43485. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43486. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43487. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43488. this._uniformBuffer.addUniform("specularMatrix", 16);
  43489. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43490. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43491. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43492. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43493. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43494. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43495. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43496. this._uniformBuffer.addUniform("pointSize", 1);
  43497. this._uniformBuffer.create();
  43498. };
  43499. StandardMaterial.prototype.unbind = function () {
  43500. if (this._activeEffect) {
  43501. var needFlag = false;
  43502. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43503. this._activeEffect.setTexture("reflection2DSampler", null);
  43504. needFlag = true;
  43505. }
  43506. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43507. this._activeEffect.setTexture("refraction2DSampler", null);
  43508. needFlag = true;
  43509. }
  43510. if (needFlag) {
  43511. this._markAllSubMeshesAsTexturesDirty();
  43512. }
  43513. }
  43514. _super.prototype.unbind.call(this);
  43515. };
  43516. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43517. var scene = this.getScene();
  43518. var defines = subMesh._materialDefines;
  43519. if (!defines) {
  43520. return;
  43521. }
  43522. var effect = subMesh.effect;
  43523. if (!effect) {
  43524. return;
  43525. }
  43526. this._activeEffect = effect;
  43527. // Matrices
  43528. this.bindOnlyWorldMatrix(world);
  43529. // Normal Matrix
  43530. if (defines.OBJECTSPACE_NORMALMAP) {
  43531. world.toNormalMatrix(this._normalMatrix);
  43532. this.bindOnlyNormalMatrix(this._normalMatrix);
  43533. }
  43534. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43535. // Bones
  43536. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43537. if (mustRebind) {
  43538. this._uniformBuffer.bindToEffect(effect, "Material");
  43539. this.bindViewProjection(effect);
  43540. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43541. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43542. // Fresnel
  43543. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43544. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43545. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43546. }
  43547. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43548. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43549. }
  43550. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43551. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43552. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43553. }
  43554. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43555. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43556. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43557. }
  43558. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43559. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43560. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43561. }
  43562. }
  43563. // Textures
  43564. if (scene.texturesEnabled) {
  43565. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43566. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43567. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43568. if (this._diffuseTexture.hasAlpha) {
  43569. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43570. }
  43571. }
  43572. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43573. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43574. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43575. }
  43576. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43577. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43578. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43579. }
  43580. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43581. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43582. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43583. if (this._reflectionTexture.boundingBoxSize) {
  43584. var cubeTexture = this._reflectionTexture;
  43585. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43586. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43587. }
  43588. }
  43589. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43590. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43591. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43592. }
  43593. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43594. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43595. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43596. }
  43597. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43598. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43599. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43600. }
  43601. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43602. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43603. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43604. if (scene._mirroredCameraPosition) {
  43605. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43606. }
  43607. else {
  43608. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43609. }
  43610. }
  43611. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43612. var depth = 1.0;
  43613. if (!this._refractionTexture.isCube) {
  43614. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43615. if (this._refractionTexture.depth) {
  43616. depth = this._refractionTexture.depth;
  43617. }
  43618. }
  43619. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43620. }
  43621. }
  43622. // Point size
  43623. if (this.pointsCloud) {
  43624. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43625. }
  43626. if (defines.SPECULARTERM) {
  43627. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43628. }
  43629. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43630. // Diffuse
  43631. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43632. }
  43633. // Textures
  43634. if (scene.texturesEnabled) {
  43635. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43636. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43637. }
  43638. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43639. effect.setTexture("ambientSampler", this._ambientTexture);
  43640. }
  43641. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43642. effect.setTexture("opacitySampler", this._opacityTexture);
  43643. }
  43644. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43645. if (this._reflectionTexture.isCube) {
  43646. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43647. }
  43648. else {
  43649. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43650. }
  43651. }
  43652. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43653. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43654. }
  43655. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43656. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43657. }
  43658. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43659. effect.setTexture("specularSampler", this._specularTexture);
  43660. }
  43661. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43662. effect.setTexture("bumpSampler", this._bumpTexture);
  43663. }
  43664. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43665. var depth = 1.0;
  43666. if (this._refractionTexture.isCube) {
  43667. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43668. }
  43669. else {
  43670. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43671. }
  43672. }
  43673. }
  43674. // Clip plane
  43675. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43676. // Colors
  43677. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43678. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43679. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43680. }
  43681. if (mustRebind || !this.isFrozen) {
  43682. // Lights
  43683. if (scene.lightsEnabled && !this._disableLighting) {
  43684. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43685. }
  43686. // View
  43687. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43688. this.bindView(effect);
  43689. }
  43690. // Fog
  43691. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43692. // Morph targets
  43693. if (defines.NUM_MORPH_INFLUENCERS) {
  43694. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43695. }
  43696. // Log. depth
  43697. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43698. // image processing
  43699. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43700. this._imageProcessingConfiguration.bind(this._activeEffect);
  43701. }
  43702. }
  43703. this._uniformBuffer.update();
  43704. this._afterBind(mesh, this._activeEffect);
  43705. };
  43706. StandardMaterial.prototype.getAnimatables = function () {
  43707. var results = [];
  43708. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43709. results.push(this._diffuseTexture);
  43710. }
  43711. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43712. results.push(this._ambientTexture);
  43713. }
  43714. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43715. results.push(this._opacityTexture);
  43716. }
  43717. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43718. results.push(this._reflectionTexture);
  43719. }
  43720. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43721. results.push(this._emissiveTexture);
  43722. }
  43723. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43724. results.push(this._specularTexture);
  43725. }
  43726. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43727. results.push(this._bumpTexture);
  43728. }
  43729. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43730. results.push(this._lightmapTexture);
  43731. }
  43732. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43733. results.push(this._refractionTexture);
  43734. }
  43735. return results;
  43736. };
  43737. StandardMaterial.prototype.getActiveTextures = function () {
  43738. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43739. if (this._diffuseTexture) {
  43740. activeTextures.push(this._diffuseTexture);
  43741. }
  43742. if (this._ambientTexture) {
  43743. activeTextures.push(this._ambientTexture);
  43744. }
  43745. if (this._opacityTexture) {
  43746. activeTextures.push(this._opacityTexture);
  43747. }
  43748. if (this._reflectionTexture) {
  43749. activeTextures.push(this._reflectionTexture);
  43750. }
  43751. if (this._emissiveTexture) {
  43752. activeTextures.push(this._emissiveTexture);
  43753. }
  43754. if (this._specularTexture) {
  43755. activeTextures.push(this._specularTexture);
  43756. }
  43757. if (this._bumpTexture) {
  43758. activeTextures.push(this._bumpTexture);
  43759. }
  43760. if (this._lightmapTexture) {
  43761. activeTextures.push(this._lightmapTexture);
  43762. }
  43763. if (this._refractionTexture) {
  43764. activeTextures.push(this._refractionTexture);
  43765. }
  43766. return activeTextures;
  43767. };
  43768. StandardMaterial.prototype.hasTexture = function (texture) {
  43769. if (_super.prototype.hasTexture.call(this, texture)) {
  43770. return true;
  43771. }
  43772. if (this._diffuseTexture === texture) {
  43773. return true;
  43774. }
  43775. if (this._ambientTexture === texture) {
  43776. return true;
  43777. }
  43778. if (this._opacityTexture === texture) {
  43779. return true;
  43780. }
  43781. if (this._reflectionTexture === texture) {
  43782. return true;
  43783. }
  43784. if (this._emissiveTexture === texture) {
  43785. return true;
  43786. }
  43787. if (this._specularTexture === texture) {
  43788. return true;
  43789. }
  43790. if (this._bumpTexture === texture) {
  43791. return true;
  43792. }
  43793. if (this._lightmapTexture === texture) {
  43794. return true;
  43795. }
  43796. if (this._refractionTexture === texture) {
  43797. return true;
  43798. }
  43799. return false;
  43800. };
  43801. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43802. if (forceDisposeTextures) {
  43803. if (this._diffuseTexture) {
  43804. this._diffuseTexture.dispose();
  43805. }
  43806. if (this._ambientTexture) {
  43807. this._ambientTexture.dispose();
  43808. }
  43809. if (this._opacityTexture) {
  43810. this._opacityTexture.dispose();
  43811. }
  43812. if (this._reflectionTexture) {
  43813. this._reflectionTexture.dispose();
  43814. }
  43815. if (this._emissiveTexture) {
  43816. this._emissiveTexture.dispose();
  43817. }
  43818. if (this._specularTexture) {
  43819. this._specularTexture.dispose();
  43820. }
  43821. if (this._bumpTexture) {
  43822. this._bumpTexture.dispose();
  43823. }
  43824. if (this._lightmapTexture) {
  43825. this._lightmapTexture.dispose();
  43826. }
  43827. if (this._refractionTexture) {
  43828. this._refractionTexture.dispose();
  43829. }
  43830. }
  43831. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43832. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43833. }
  43834. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43835. };
  43836. StandardMaterial.prototype.clone = function (name) {
  43837. var _this = this;
  43838. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43839. result.name = name;
  43840. result.id = name;
  43841. return result;
  43842. };
  43843. StandardMaterial.prototype.serialize = function () {
  43844. return BABYLON.SerializationHelper.Serialize(this);
  43845. };
  43846. // Statics
  43847. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43848. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43849. };
  43850. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43851. get: function () {
  43852. return StandardMaterial._DiffuseTextureEnabled;
  43853. },
  43854. set: function (value) {
  43855. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43856. return;
  43857. }
  43858. StandardMaterial._DiffuseTextureEnabled = value;
  43859. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43860. },
  43861. enumerable: true,
  43862. configurable: true
  43863. });
  43864. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43865. get: function () {
  43866. return StandardMaterial._AmbientTextureEnabled;
  43867. },
  43868. set: function (value) {
  43869. if (StandardMaterial._AmbientTextureEnabled === value) {
  43870. return;
  43871. }
  43872. StandardMaterial._AmbientTextureEnabled = value;
  43873. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43874. },
  43875. enumerable: true,
  43876. configurable: true
  43877. });
  43878. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43879. get: function () {
  43880. return StandardMaterial._OpacityTextureEnabled;
  43881. },
  43882. set: function (value) {
  43883. if (StandardMaterial._OpacityTextureEnabled === value) {
  43884. return;
  43885. }
  43886. StandardMaterial._OpacityTextureEnabled = value;
  43887. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43888. },
  43889. enumerable: true,
  43890. configurable: true
  43891. });
  43892. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43893. get: function () {
  43894. return StandardMaterial._ReflectionTextureEnabled;
  43895. },
  43896. set: function (value) {
  43897. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43898. return;
  43899. }
  43900. StandardMaterial._ReflectionTextureEnabled = value;
  43901. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43902. },
  43903. enumerable: true,
  43904. configurable: true
  43905. });
  43906. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43907. get: function () {
  43908. return StandardMaterial._EmissiveTextureEnabled;
  43909. },
  43910. set: function (value) {
  43911. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43912. return;
  43913. }
  43914. StandardMaterial._EmissiveTextureEnabled = value;
  43915. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43916. },
  43917. enumerable: true,
  43918. configurable: true
  43919. });
  43920. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43921. get: function () {
  43922. return StandardMaterial._SpecularTextureEnabled;
  43923. },
  43924. set: function (value) {
  43925. if (StandardMaterial._SpecularTextureEnabled === value) {
  43926. return;
  43927. }
  43928. StandardMaterial._SpecularTextureEnabled = value;
  43929. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43930. },
  43931. enumerable: true,
  43932. configurable: true
  43933. });
  43934. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43935. get: function () {
  43936. return StandardMaterial._BumpTextureEnabled;
  43937. },
  43938. set: function (value) {
  43939. if (StandardMaterial._BumpTextureEnabled === value) {
  43940. return;
  43941. }
  43942. StandardMaterial._BumpTextureEnabled = value;
  43943. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43944. },
  43945. enumerable: true,
  43946. configurable: true
  43947. });
  43948. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43949. get: function () {
  43950. return StandardMaterial._LightmapTextureEnabled;
  43951. },
  43952. set: function (value) {
  43953. if (StandardMaterial._LightmapTextureEnabled === value) {
  43954. return;
  43955. }
  43956. StandardMaterial._LightmapTextureEnabled = value;
  43957. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43958. },
  43959. enumerable: true,
  43960. configurable: true
  43961. });
  43962. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43963. get: function () {
  43964. return StandardMaterial._RefractionTextureEnabled;
  43965. },
  43966. set: function (value) {
  43967. if (StandardMaterial._RefractionTextureEnabled === value) {
  43968. return;
  43969. }
  43970. StandardMaterial._RefractionTextureEnabled = value;
  43971. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43972. },
  43973. enumerable: true,
  43974. configurable: true
  43975. });
  43976. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43977. get: function () {
  43978. return StandardMaterial._ColorGradingTextureEnabled;
  43979. },
  43980. set: function (value) {
  43981. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43982. return;
  43983. }
  43984. StandardMaterial._ColorGradingTextureEnabled = value;
  43985. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43986. },
  43987. enumerable: true,
  43988. configurable: true
  43989. });
  43990. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43991. get: function () {
  43992. return StandardMaterial._FresnelEnabled;
  43993. },
  43994. set: function (value) {
  43995. if (StandardMaterial._FresnelEnabled === value) {
  43996. return;
  43997. }
  43998. StandardMaterial._FresnelEnabled = value;
  43999. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44000. },
  44001. enumerable: true,
  44002. configurable: true
  44003. });
  44004. // Flags used to enable or disable a type of texture for all Standard Materials
  44005. StandardMaterial._DiffuseTextureEnabled = true;
  44006. StandardMaterial._AmbientTextureEnabled = true;
  44007. StandardMaterial._OpacityTextureEnabled = true;
  44008. StandardMaterial._ReflectionTextureEnabled = true;
  44009. StandardMaterial._EmissiveTextureEnabled = true;
  44010. StandardMaterial._SpecularTextureEnabled = true;
  44011. StandardMaterial._BumpTextureEnabled = true;
  44012. StandardMaterial._LightmapTextureEnabled = true;
  44013. StandardMaterial._RefractionTextureEnabled = true;
  44014. StandardMaterial._ColorGradingTextureEnabled = true;
  44015. StandardMaterial._FresnelEnabled = true;
  44016. __decorate([
  44017. BABYLON.serializeAsTexture("diffuseTexture")
  44018. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44019. __decorate([
  44020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44021. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44022. __decorate([
  44023. BABYLON.serializeAsTexture("ambientTexture")
  44024. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44025. __decorate([
  44026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44027. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44028. __decorate([
  44029. BABYLON.serializeAsTexture("opacityTexture")
  44030. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44031. __decorate([
  44032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44033. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44034. __decorate([
  44035. BABYLON.serializeAsTexture("reflectionTexture")
  44036. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44037. __decorate([
  44038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44039. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44040. __decorate([
  44041. BABYLON.serializeAsTexture("emissiveTexture")
  44042. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44043. __decorate([
  44044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44045. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44046. __decorate([
  44047. BABYLON.serializeAsTexture("specularTexture")
  44048. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44049. __decorate([
  44050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44051. ], StandardMaterial.prototype, "specularTexture", void 0);
  44052. __decorate([
  44053. BABYLON.serializeAsTexture("bumpTexture")
  44054. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44055. __decorate([
  44056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44057. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44058. __decorate([
  44059. BABYLON.serializeAsTexture("lightmapTexture")
  44060. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44061. __decorate([
  44062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44063. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44064. __decorate([
  44065. BABYLON.serializeAsTexture("refractionTexture")
  44066. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44067. __decorate([
  44068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44069. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44070. __decorate([
  44071. BABYLON.serializeAsColor3("ambient")
  44072. ], StandardMaterial.prototype, "ambientColor", void 0);
  44073. __decorate([
  44074. BABYLON.serializeAsColor3("diffuse")
  44075. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44076. __decorate([
  44077. BABYLON.serializeAsColor3("specular")
  44078. ], StandardMaterial.prototype, "specularColor", void 0);
  44079. __decorate([
  44080. BABYLON.serializeAsColor3("emissive")
  44081. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44082. __decorate([
  44083. BABYLON.serialize()
  44084. ], StandardMaterial.prototype, "specularPower", void 0);
  44085. __decorate([
  44086. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44087. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44088. __decorate([
  44089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44090. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44091. __decorate([
  44092. BABYLON.serialize("useEmissiveAsIllumination")
  44093. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44094. __decorate([
  44095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44096. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44097. __decorate([
  44098. BABYLON.serialize("linkEmissiveWithDiffuse")
  44099. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44100. __decorate([
  44101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44102. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44103. __decorate([
  44104. BABYLON.serialize("useSpecularOverAlpha")
  44105. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44106. __decorate([
  44107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44108. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44109. __decorate([
  44110. BABYLON.serialize("useReflectionOverAlpha")
  44111. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44112. __decorate([
  44113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44114. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44115. __decorate([
  44116. BABYLON.serialize("disableLighting")
  44117. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44118. __decorate([
  44119. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44120. ], StandardMaterial.prototype, "disableLighting", void 0);
  44121. __decorate([
  44122. BABYLON.serialize("useObjectSpaceNormalMap")
  44123. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44124. __decorate([
  44125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44126. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44127. __decorate([
  44128. BABYLON.serialize("useParallax")
  44129. ], StandardMaterial.prototype, "_useParallax", void 0);
  44130. __decorate([
  44131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44132. ], StandardMaterial.prototype, "useParallax", void 0);
  44133. __decorate([
  44134. BABYLON.serialize("useParallaxOcclusion")
  44135. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44136. __decorate([
  44137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44138. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44139. __decorate([
  44140. BABYLON.serialize()
  44141. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44142. __decorate([
  44143. BABYLON.serialize("roughness")
  44144. ], StandardMaterial.prototype, "_roughness", void 0);
  44145. __decorate([
  44146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44147. ], StandardMaterial.prototype, "roughness", void 0);
  44148. __decorate([
  44149. BABYLON.serialize()
  44150. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44151. __decorate([
  44152. BABYLON.serialize()
  44153. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44154. __decorate([
  44155. BABYLON.serialize()
  44156. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44157. __decorate([
  44158. BABYLON.serialize("useLightmapAsShadowmap")
  44159. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44160. __decorate([
  44161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44162. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44163. __decorate([
  44164. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44165. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44166. __decorate([
  44167. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44168. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44169. __decorate([
  44170. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44171. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44172. __decorate([
  44173. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44174. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44175. __decorate([
  44176. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44177. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44178. __decorate([
  44179. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44180. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44181. __decorate([
  44182. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44183. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44184. __decorate([
  44185. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44186. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44187. __decorate([
  44188. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44189. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44190. __decorate([
  44191. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44192. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44193. __decorate([
  44194. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44195. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44196. __decorate([
  44197. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44198. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44199. __decorate([
  44200. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44201. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44202. __decorate([
  44203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44204. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44205. __decorate([
  44206. BABYLON.serialize("maxSimultaneousLights")
  44207. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44208. __decorate([
  44209. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44210. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44211. __decorate([
  44212. BABYLON.serialize("invertNormalMapX")
  44213. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44214. __decorate([
  44215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44216. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44217. __decorate([
  44218. BABYLON.serialize("invertNormalMapY")
  44219. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44220. __decorate([
  44221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44222. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44223. __decorate([
  44224. BABYLON.serialize("twoSidedLighting")
  44225. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44226. __decorate([
  44227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44228. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44229. __decorate([
  44230. BABYLON.serialize()
  44231. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44232. return StandardMaterial;
  44233. }(BABYLON.PushMaterial));
  44234. BABYLON.StandardMaterial = StandardMaterial;
  44235. })(BABYLON || (BABYLON = {}));
  44236. //# sourceMappingURL=babylon.standardMaterial.js.map
  44237. var BABYLON;
  44238. (function (BABYLON) {
  44239. /**
  44240. * Manages the defines for the PBR Material.
  44241. * @hiddenChildren
  44242. */
  44243. var PBRMaterialDefines = /** @class */ (function (_super) {
  44244. __extends(PBRMaterialDefines, _super);
  44245. /**
  44246. * Initializes the PBR Material defines.
  44247. */
  44248. function PBRMaterialDefines() {
  44249. var _this = _super.call(this) || this;
  44250. _this.PBR = true;
  44251. _this.MAINUV1 = false;
  44252. _this.MAINUV2 = false;
  44253. _this.UV1 = false;
  44254. _this.UV2 = false;
  44255. _this.ALBEDO = false;
  44256. _this.ALBEDODIRECTUV = 0;
  44257. _this.VERTEXCOLOR = false;
  44258. _this.AMBIENT = false;
  44259. _this.AMBIENTDIRECTUV = 0;
  44260. _this.AMBIENTINGRAYSCALE = false;
  44261. _this.OPACITY = false;
  44262. _this.VERTEXALPHA = false;
  44263. _this.OPACITYDIRECTUV = 0;
  44264. _this.OPACITYRGB = false;
  44265. _this.ALPHATEST = false;
  44266. _this.DEPTHPREPASS = false;
  44267. _this.ALPHABLEND = false;
  44268. _this.ALPHAFROMALBEDO = false;
  44269. _this.ALPHATESTVALUE = "0.5";
  44270. _this.SPECULAROVERALPHA = false;
  44271. _this.RADIANCEOVERALPHA = false;
  44272. _this.ALPHAFRESNEL = false;
  44273. _this.LINEARALPHAFRESNEL = false;
  44274. _this.PREMULTIPLYALPHA = false;
  44275. _this.EMISSIVE = false;
  44276. _this.EMISSIVEDIRECTUV = 0;
  44277. _this.REFLECTIVITY = false;
  44278. _this.REFLECTIVITYDIRECTUV = 0;
  44279. _this.SPECULARTERM = false;
  44280. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44281. _this.MICROSURFACEAUTOMATIC = false;
  44282. _this.LODBASEDMICROSFURACE = false;
  44283. _this.MICROSURFACEMAP = false;
  44284. _this.MICROSURFACEMAPDIRECTUV = 0;
  44285. _this.METALLICWORKFLOW = false;
  44286. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44287. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44288. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44289. _this.AOSTOREINMETALMAPRED = false;
  44290. _this.ENVIRONMENTBRDF = false;
  44291. _this.NORMAL = false;
  44292. _this.TANGENT = false;
  44293. _this.BUMP = false;
  44294. _this.BUMPDIRECTUV = 0;
  44295. _this.OBJECTSPACE_NORMALMAP = false;
  44296. _this.PARALLAX = false;
  44297. _this.PARALLAXOCCLUSION = false;
  44298. _this.NORMALXYSCALE = true;
  44299. _this.LIGHTMAP = false;
  44300. _this.LIGHTMAPDIRECTUV = 0;
  44301. _this.USELIGHTMAPASSHADOWMAP = false;
  44302. _this.GAMMALIGHTMAP = false;
  44303. _this.REFLECTION = false;
  44304. _this.REFLECTIONMAP_3D = false;
  44305. _this.REFLECTIONMAP_SPHERICAL = false;
  44306. _this.REFLECTIONMAP_PLANAR = false;
  44307. _this.REFLECTIONMAP_CUBIC = false;
  44308. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44309. _this.REFLECTIONMAP_PROJECTION = false;
  44310. _this.REFLECTIONMAP_SKYBOX = false;
  44311. _this.REFLECTIONMAP_EXPLICIT = false;
  44312. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44313. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44314. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44315. _this.INVERTCUBICMAP = false;
  44316. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44317. _this.USESPHERICALINVERTEX = false;
  44318. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44319. _this.LODINREFLECTIONALPHA = false;
  44320. _this.GAMMAREFLECTION = false;
  44321. _this.RADIANCEOCCLUSION = false;
  44322. _this.HORIZONOCCLUSION = false;
  44323. _this.REFRACTION = false;
  44324. _this.REFRACTIONMAP_3D = false;
  44325. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44326. _this.LODINREFRACTIONALPHA = false;
  44327. _this.GAMMAREFRACTION = false;
  44328. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44329. _this.INSTANCES = false;
  44330. _this.NUM_BONE_INFLUENCERS = 0;
  44331. _this.BonesPerMesh = 0;
  44332. _this.NONUNIFORMSCALING = false;
  44333. _this.MORPHTARGETS = false;
  44334. _this.MORPHTARGETS_NORMAL = false;
  44335. _this.MORPHTARGETS_TANGENT = false;
  44336. _this.NUM_MORPH_INFLUENCERS = 0;
  44337. _this.IMAGEPROCESSING = false;
  44338. _this.VIGNETTE = false;
  44339. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44340. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44341. _this.TONEMAPPING = false;
  44342. _this.CONTRAST = false;
  44343. _this.COLORCURVES = false;
  44344. _this.COLORGRADING = false;
  44345. _this.COLORGRADING3D = false;
  44346. _this.SAMPLER3DGREENDEPTH = false;
  44347. _this.SAMPLER3DBGRMAP = false;
  44348. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44349. _this.EXPOSURE = false;
  44350. _this.USEPHYSICALLIGHTFALLOFF = false;
  44351. _this.TWOSIDEDLIGHTING = false;
  44352. _this.SHADOWFLOAT = false;
  44353. _this.CLIPPLANE = false;
  44354. _this.POINTSIZE = false;
  44355. _this.FOG = false;
  44356. _this.LOGARITHMICDEPTH = false;
  44357. _this.FORCENORMALFORWARD = false;
  44358. _this.SPECULARAA = false;
  44359. _this.UNLIT = false;
  44360. _this.rebuild();
  44361. return _this;
  44362. }
  44363. /**
  44364. * Resets the PBR Material defines.
  44365. */
  44366. PBRMaterialDefines.prototype.reset = function () {
  44367. _super.prototype.reset.call(this);
  44368. this.ALPHATESTVALUE = "0.5";
  44369. this.PBR = true;
  44370. };
  44371. return PBRMaterialDefines;
  44372. }(BABYLON.MaterialDefines));
  44373. /**
  44374. * The Physically based material base class of BJS.
  44375. *
  44376. * This offers the main features of a standard PBR material.
  44377. * For more information, please refer to the documentation :
  44378. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44379. */
  44380. var PBRBaseMaterial = /** @class */ (function (_super) {
  44381. __extends(PBRBaseMaterial, _super);
  44382. /**
  44383. * Instantiates a new PBRMaterial instance.
  44384. *
  44385. * @param name The material name
  44386. * @param scene The scene the material will be use in.
  44387. */
  44388. function PBRBaseMaterial(name, scene) {
  44389. var _this = _super.call(this, name, scene) || this;
  44390. /**
  44391. * Intensity of the direct lights e.g. the four lights available in your scene.
  44392. * This impacts both the direct diffuse and specular highlights.
  44393. */
  44394. _this._directIntensity = 1.0;
  44395. /**
  44396. * Intensity of the emissive part of the material.
  44397. * This helps controlling the emissive effect without modifying the emissive color.
  44398. */
  44399. _this._emissiveIntensity = 1.0;
  44400. /**
  44401. * Intensity of the environment e.g. how much the environment will light the object
  44402. * either through harmonics for rough material or through the refelction for shiny ones.
  44403. */
  44404. _this._environmentIntensity = 1.0;
  44405. /**
  44406. * This is a special control allowing the reduction of the specular highlights coming from the
  44407. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44408. */
  44409. _this._specularIntensity = 1.0;
  44410. /**
  44411. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44412. */
  44413. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44414. /**
  44415. * Debug Control allowing disabling the bump map on this material.
  44416. */
  44417. _this._disableBumpMap = false;
  44418. /**
  44419. * AKA Occlusion Texture Intensity in other nomenclature.
  44420. */
  44421. _this._ambientTextureStrength = 1.0;
  44422. /**
  44423. * The color of a material in ambient lighting.
  44424. */
  44425. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44426. /**
  44427. * AKA Diffuse Color in other nomenclature.
  44428. */
  44429. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44430. /**
  44431. * AKA Specular Color in other nomenclature.
  44432. */
  44433. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44434. /**
  44435. * The color applied when light is reflected from a material.
  44436. */
  44437. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44438. /**
  44439. * The color applied when light is emitted from a material.
  44440. */
  44441. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44442. /**
  44443. * AKA Glossiness in other nomenclature.
  44444. */
  44445. _this._microSurface = 0.9;
  44446. /**
  44447. * source material index of refraction (IOR)' / 'destination material IOR.
  44448. */
  44449. _this._indexOfRefraction = 0.66;
  44450. /**
  44451. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44452. */
  44453. _this._invertRefractionY = false;
  44454. /**
  44455. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44456. * Materials half opaque for instance using refraction could benefit from this control.
  44457. */
  44458. _this._linkRefractionWithTransparency = false;
  44459. /**
  44460. * Specifies that the material will use the light map as a show map.
  44461. */
  44462. _this._useLightmapAsShadowmap = false;
  44463. /**
  44464. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44465. * makes the reflect vector face the model (under horizon).
  44466. */
  44467. _this._useHorizonOcclusion = true;
  44468. /**
  44469. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44470. * too much the area relying on ambient texture to define their ambient occlusion.
  44471. */
  44472. _this._useRadianceOcclusion = true;
  44473. /**
  44474. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44475. */
  44476. _this._useAlphaFromAlbedoTexture = false;
  44477. /**
  44478. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44479. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44480. */
  44481. _this._useSpecularOverAlpha = true;
  44482. /**
  44483. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44484. */
  44485. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44486. /**
  44487. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44488. */
  44489. _this._useRoughnessFromMetallicTextureAlpha = true;
  44490. /**
  44491. * Specifies if the metallic texture contains the roughness information in its green channel.
  44492. */
  44493. _this._useRoughnessFromMetallicTextureGreen = false;
  44494. /**
  44495. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44496. */
  44497. _this._useMetallnessFromMetallicTextureBlue = false;
  44498. /**
  44499. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44500. */
  44501. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44502. /**
  44503. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44504. */
  44505. _this._useAmbientInGrayScale = false;
  44506. /**
  44507. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44508. * The material will try to infer what glossiness each pixel should be.
  44509. */
  44510. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44511. /**
  44512. * BJS is using an harcoded light falloff based on a manually sets up range.
  44513. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44514. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44515. */
  44516. _this._usePhysicalLightFalloff = true;
  44517. /**
  44518. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44519. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44520. */
  44521. _this._useRadianceOverAlpha = true;
  44522. /**
  44523. * Allows using an object space normal map (instead of tangent space).
  44524. */
  44525. _this._useObjectSpaceNormalMap = false;
  44526. /**
  44527. * Allows using the bump map in parallax mode.
  44528. */
  44529. _this._useParallax = false;
  44530. /**
  44531. * Allows using the bump map in parallax occlusion mode.
  44532. */
  44533. _this._useParallaxOcclusion = false;
  44534. /**
  44535. * Controls the scale bias of the parallax mode.
  44536. */
  44537. _this._parallaxScaleBias = 0.05;
  44538. /**
  44539. * If sets to true, disables all the lights affecting the material.
  44540. */
  44541. _this._disableLighting = false;
  44542. /**
  44543. * Number of Simultaneous lights allowed on the material.
  44544. */
  44545. _this._maxSimultaneousLights = 4;
  44546. /**
  44547. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44548. */
  44549. _this._invertNormalMapX = false;
  44550. /**
  44551. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44552. */
  44553. _this._invertNormalMapY = false;
  44554. /**
  44555. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44556. */
  44557. _this._twoSidedLighting = false;
  44558. /**
  44559. * Defines the alpha limits in alpha test mode.
  44560. */
  44561. _this._alphaCutOff = 0.4;
  44562. /**
  44563. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44564. */
  44565. _this._forceAlphaTest = false;
  44566. /**
  44567. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44568. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44569. */
  44570. _this._useAlphaFresnel = false;
  44571. /**
  44572. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44573. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44574. */
  44575. _this._useLinearAlphaFresnel = false;
  44576. /**
  44577. * The transparency mode of the material.
  44578. */
  44579. _this._transparencyMode = null;
  44580. /**
  44581. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44582. * from cos thetav and roughness:
  44583. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44584. */
  44585. _this._environmentBRDFTexture = null;
  44586. /**
  44587. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44588. */
  44589. _this._forceIrradianceInFragment = false;
  44590. /**
  44591. * Force normal to face away from face.
  44592. */
  44593. _this._forceNormalForward = false;
  44594. /**
  44595. * Enables specular anti aliasing in the PBR shader.
  44596. * It will both interacts on the Geometry for analytical and IBL lighting.
  44597. * It also prefilter the roughness map based on the bump values.
  44598. */
  44599. _this._enableSpecularAntiAliasing = false;
  44600. /**
  44601. * Stores the available render targets.
  44602. */
  44603. _this._renderTargets = new BABYLON.SmartArray(16);
  44604. /**
  44605. * Sets the global ambient color for the material used in lighting calculations.
  44606. */
  44607. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44608. /**
  44609. * If set to true, no lighting calculations will be applied.
  44610. */
  44611. _this._unlit = false;
  44612. // Setup the default processing configuration to the scene.
  44613. _this._attachImageProcessingConfiguration(null);
  44614. _this.getRenderTargetTextures = function () {
  44615. _this._renderTargets.reset();
  44616. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44617. _this._renderTargets.push(_this._reflectionTexture);
  44618. }
  44619. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44620. _this._renderTargets.push(_this._refractionTexture);
  44621. }
  44622. return _this._renderTargets;
  44623. };
  44624. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44625. return _this;
  44626. }
  44627. /**
  44628. * Attaches a new image processing configuration to the PBR Material.
  44629. * @param configuration
  44630. */
  44631. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44632. var _this = this;
  44633. if (configuration === this._imageProcessingConfiguration) {
  44634. return;
  44635. }
  44636. // Detaches observer.
  44637. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44638. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44639. }
  44640. // Pick the scene configuration if needed.
  44641. if (!configuration) {
  44642. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44643. }
  44644. else {
  44645. this._imageProcessingConfiguration = configuration;
  44646. }
  44647. // Attaches observer.
  44648. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44649. _this._markAllSubMeshesAsImageProcessingDirty();
  44650. });
  44651. };
  44652. /**
  44653. * Gets the name of the material class.
  44654. */
  44655. PBRBaseMaterial.prototype.getClassName = function () {
  44656. return "PBRBaseMaterial";
  44657. };
  44658. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44659. /**
  44660. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44661. */
  44662. get: function () {
  44663. return this._useLogarithmicDepth;
  44664. },
  44665. /**
  44666. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44667. */
  44668. set: function (value) {
  44669. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44670. },
  44671. enumerable: true,
  44672. configurable: true
  44673. });
  44674. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44675. /**
  44676. * Gets the current transparency mode.
  44677. */
  44678. get: function () {
  44679. return this._transparencyMode;
  44680. },
  44681. /**
  44682. * Sets the transparency mode of the material.
  44683. */
  44684. set: function (value) {
  44685. if (this._transparencyMode === value) {
  44686. return;
  44687. }
  44688. this._transparencyMode = value;
  44689. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44690. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44691. },
  44692. enumerable: true,
  44693. configurable: true
  44694. });
  44695. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44696. /**
  44697. * Returns true if alpha blending should be disabled.
  44698. */
  44699. get: function () {
  44700. return (this._linkRefractionWithTransparency ||
  44701. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44702. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44703. },
  44704. enumerable: true,
  44705. configurable: true
  44706. });
  44707. /**
  44708. * Specifies whether or not this material should be rendered in alpha blend mode.
  44709. */
  44710. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44711. if (this._disableAlphaBlending) {
  44712. return false;
  44713. }
  44714. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44715. };
  44716. /**
  44717. * Specifies if the mesh will require alpha blending.
  44718. * @param mesh - BJS mesh.
  44719. */
  44720. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44721. if (this._disableAlphaBlending) {
  44722. return false;
  44723. }
  44724. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44725. };
  44726. /**
  44727. * Specifies whether or not this material should be rendered in alpha test mode.
  44728. */
  44729. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44730. if (this._forceAlphaTest) {
  44731. return true;
  44732. }
  44733. if (this._linkRefractionWithTransparency) {
  44734. return false;
  44735. }
  44736. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44737. };
  44738. /**
  44739. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44740. */
  44741. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44742. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44743. };
  44744. /**
  44745. * Gets the texture used for the alpha test.
  44746. */
  44747. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44748. return this._albedoTexture;
  44749. };
  44750. /**
  44751. * Specifies that the submesh is ready to be used.
  44752. * @param mesh - BJS mesh.
  44753. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44754. * @param useInstances - Specifies that instances should be used.
  44755. * @returns - boolean indicating that the submesh is ready or not.
  44756. */
  44757. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44758. if (subMesh.effect && this.isFrozen) {
  44759. if (this._wasPreviouslyReady) {
  44760. return true;
  44761. }
  44762. }
  44763. if (!subMesh._materialDefines) {
  44764. subMesh._materialDefines = new PBRMaterialDefines();
  44765. }
  44766. var defines = subMesh._materialDefines;
  44767. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44768. if (defines._renderId === this.getScene().getRenderId()) {
  44769. return true;
  44770. }
  44771. }
  44772. var scene = this.getScene();
  44773. var engine = scene.getEngine();
  44774. if (defines._areTexturesDirty) {
  44775. if (scene.texturesEnabled) {
  44776. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44777. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44778. return false;
  44779. }
  44780. }
  44781. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44782. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44783. return false;
  44784. }
  44785. }
  44786. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44787. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44788. return false;
  44789. }
  44790. }
  44791. var reflectionTexture = this._getReflectionTexture();
  44792. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44793. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44794. return false;
  44795. }
  44796. }
  44797. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44798. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44799. return false;
  44800. }
  44801. }
  44802. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44803. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44804. return false;
  44805. }
  44806. }
  44807. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44808. if (this._metallicTexture) {
  44809. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44810. return false;
  44811. }
  44812. }
  44813. else if (this._reflectivityTexture) {
  44814. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44815. return false;
  44816. }
  44817. }
  44818. if (this._microSurfaceTexture) {
  44819. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44820. return false;
  44821. }
  44822. }
  44823. }
  44824. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44825. // Bump texture cannot be not blocking.
  44826. if (!this._bumpTexture.isReady()) {
  44827. return false;
  44828. }
  44829. }
  44830. var refractionTexture = this._getRefractionTexture();
  44831. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44832. if (!refractionTexture.isReadyOrNotBlocking()) {
  44833. return false;
  44834. }
  44835. }
  44836. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44837. // This is blocking.
  44838. if (!this._environmentBRDFTexture.isReady()) {
  44839. return false;
  44840. }
  44841. }
  44842. }
  44843. }
  44844. if (defines._areImageProcessingDirty) {
  44845. if (!this._imageProcessingConfiguration.isReady()) {
  44846. return false;
  44847. }
  44848. }
  44849. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44850. mesh.createNormals(true);
  44851. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44852. }
  44853. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44854. if (effect) {
  44855. scene.resetCachedMaterial();
  44856. subMesh.setEffect(effect, defines);
  44857. this.buildUniformLayout();
  44858. }
  44859. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44860. return false;
  44861. }
  44862. defines._renderId = scene.getRenderId();
  44863. this._wasPreviouslyReady = true;
  44864. return true;
  44865. };
  44866. /**
  44867. * Specifies if the material uses metallic roughness workflow.
  44868. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44869. */
  44870. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44871. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44872. return true;
  44873. }
  44874. return false;
  44875. };
  44876. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44877. if (onCompiled === void 0) { onCompiled = null; }
  44878. if (onError === void 0) { onError = null; }
  44879. if (useInstances === void 0) { useInstances = null; }
  44880. if (useClipPlane === void 0) { useClipPlane = null; }
  44881. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44882. if (!defines.isDirty) {
  44883. return null;
  44884. }
  44885. defines.markAsProcessed();
  44886. var scene = this.getScene();
  44887. var engine = scene.getEngine();
  44888. // Fallbacks
  44889. var fallbacks = new BABYLON.EffectFallbacks();
  44890. var fallbackRank = 0;
  44891. if (defines.USESPHERICALINVERTEX) {
  44892. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44893. }
  44894. if (defines.FOG) {
  44895. fallbacks.addFallback(fallbackRank, "FOG");
  44896. }
  44897. if (defines.SPECULARAA) {
  44898. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44899. }
  44900. if (defines.POINTSIZE) {
  44901. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44902. }
  44903. if (defines.LOGARITHMICDEPTH) {
  44904. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44905. }
  44906. if (defines.PARALLAX) {
  44907. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44908. }
  44909. if (defines.PARALLAXOCCLUSION) {
  44910. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44911. }
  44912. if (defines.ENVIRONMENTBRDF) {
  44913. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44914. }
  44915. if (defines.TANGENT) {
  44916. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44917. }
  44918. if (defines.BUMP) {
  44919. fallbacks.addFallback(fallbackRank++, "BUMP");
  44920. }
  44921. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44922. if (defines.SPECULARTERM) {
  44923. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44924. }
  44925. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44926. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44927. }
  44928. if (defines.LIGHTMAP) {
  44929. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44930. }
  44931. if (defines.NORMAL) {
  44932. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44933. }
  44934. if (defines.AMBIENT) {
  44935. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44936. }
  44937. if (defines.EMISSIVE) {
  44938. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44939. }
  44940. if (defines.VERTEXCOLOR) {
  44941. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44942. }
  44943. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44944. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44945. }
  44946. if (defines.MORPHTARGETS) {
  44947. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44948. }
  44949. //Attributes
  44950. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44951. if (defines.NORMAL) {
  44952. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44953. }
  44954. if (defines.TANGENT) {
  44955. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44956. }
  44957. if (defines.UV1) {
  44958. attribs.push(BABYLON.VertexBuffer.UVKind);
  44959. }
  44960. if (defines.UV2) {
  44961. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44962. }
  44963. if (defines.VERTEXCOLOR) {
  44964. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44965. }
  44966. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44967. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44968. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44969. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44970. "vFogInfos", "vFogColor", "pointSize",
  44971. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44972. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44973. "mBones",
  44974. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44975. "vLightingIntensity",
  44976. "logarithmicDepthConstant",
  44977. "vSphericalX", "vSphericalY", "vSphericalZ",
  44978. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44979. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44980. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44981. "vTangentSpaceParams"
  44982. ];
  44983. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44984. "bumpSampler", "lightmapSampler", "opacitySampler",
  44985. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44986. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44987. "microSurfaceSampler", "environmentBrdfSampler"];
  44988. var uniformBuffers = ["Material", "Scene"];
  44989. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44990. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44991. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44992. uniformsNames: uniforms,
  44993. uniformBuffersNames: uniformBuffers,
  44994. samplers: samplers,
  44995. defines: defines,
  44996. maxSimultaneousLights: this._maxSimultaneousLights
  44997. });
  44998. var join = defines.toString();
  44999. return engine.createEffect("pbr", {
  45000. attributes: attribs,
  45001. uniformsNames: uniforms,
  45002. uniformBuffersNames: uniformBuffers,
  45003. samplers: samplers,
  45004. defines: join,
  45005. fallbacks: fallbacks,
  45006. onCompiled: onCompiled,
  45007. onError: onError,
  45008. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45009. }, engine);
  45010. };
  45011. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45012. if (useInstances === void 0) { useInstances = null; }
  45013. if (useClipPlane === void 0) { useClipPlane = null; }
  45014. var scene = this.getScene();
  45015. var engine = scene.getEngine();
  45016. // Lights
  45017. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45018. defines._needNormals = true;
  45019. // Textures
  45020. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45021. if (defines._areTexturesDirty) {
  45022. defines._needUVs = false;
  45023. if (scene.texturesEnabled) {
  45024. if (scene.getEngine().getCaps().textureLOD) {
  45025. defines.LODBASEDMICROSFURACE = true;
  45026. }
  45027. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45028. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45029. }
  45030. else {
  45031. defines.ALBEDO = false;
  45032. }
  45033. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45034. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45035. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45036. }
  45037. else {
  45038. defines.AMBIENT = false;
  45039. }
  45040. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45041. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45042. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45043. }
  45044. else {
  45045. defines.OPACITY = false;
  45046. }
  45047. var reflectionTexture = this._getReflectionTexture();
  45048. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45049. defines.REFLECTION = true;
  45050. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45051. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45052. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45053. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45054. defines.INVERTCUBICMAP = true;
  45055. }
  45056. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45057. switch (reflectionTexture.coordinatesMode) {
  45058. case BABYLON.Texture.EXPLICIT_MODE:
  45059. defines.REFLECTIONMAP_EXPLICIT = true;
  45060. break;
  45061. case BABYLON.Texture.PLANAR_MODE:
  45062. defines.REFLECTIONMAP_PLANAR = true;
  45063. break;
  45064. case BABYLON.Texture.PROJECTION_MODE:
  45065. defines.REFLECTIONMAP_PROJECTION = true;
  45066. break;
  45067. case BABYLON.Texture.SKYBOX_MODE:
  45068. defines.REFLECTIONMAP_SKYBOX = true;
  45069. break;
  45070. case BABYLON.Texture.SPHERICAL_MODE:
  45071. defines.REFLECTIONMAP_SPHERICAL = true;
  45072. break;
  45073. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45074. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45075. break;
  45076. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45077. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45078. break;
  45079. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45080. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45081. break;
  45082. case BABYLON.Texture.CUBIC_MODE:
  45083. case BABYLON.Texture.INVCUBIC_MODE:
  45084. default:
  45085. defines.REFLECTIONMAP_CUBIC = true;
  45086. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45087. break;
  45088. }
  45089. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45090. if (reflectionTexture.sphericalPolynomial) {
  45091. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45092. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45093. defines.USESPHERICALINVERTEX = false;
  45094. }
  45095. else {
  45096. defines.USESPHERICALINVERTEX = true;
  45097. }
  45098. }
  45099. }
  45100. }
  45101. else {
  45102. defines.REFLECTION = false;
  45103. defines.REFLECTIONMAP_3D = false;
  45104. defines.REFLECTIONMAP_SPHERICAL = false;
  45105. defines.REFLECTIONMAP_PLANAR = false;
  45106. defines.REFLECTIONMAP_CUBIC = false;
  45107. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45108. defines.REFLECTIONMAP_PROJECTION = false;
  45109. defines.REFLECTIONMAP_SKYBOX = false;
  45110. defines.REFLECTIONMAP_EXPLICIT = false;
  45111. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45112. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45113. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45114. defines.INVERTCUBICMAP = false;
  45115. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45116. defines.USESPHERICALINVERTEX = false;
  45117. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45118. defines.LODINREFLECTIONALPHA = false;
  45119. defines.GAMMAREFLECTION = false;
  45120. }
  45121. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45122. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45123. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45124. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45125. }
  45126. else {
  45127. defines.LIGHTMAP = false;
  45128. }
  45129. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45130. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45131. }
  45132. else {
  45133. defines.EMISSIVE = false;
  45134. }
  45135. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45136. if (this._metallicTexture) {
  45137. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45138. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45139. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45140. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45141. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45142. }
  45143. else if (this._reflectivityTexture) {
  45144. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45145. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45146. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45147. }
  45148. else {
  45149. defines.REFLECTIVITY = false;
  45150. }
  45151. if (this._microSurfaceTexture) {
  45152. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45153. }
  45154. else {
  45155. defines.MICROSURFACEMAP = false;
  45156. }
  45157. }
  45158. else {
  45159. defines.REFLECTIVITY = false;
  45160. defines.MICROSURFACEMAP = false;
  45161. }
  45162. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45163. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45164. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45165. defines.PARALLAX = true;
  45166. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45167. }
  45168. else {
  45169. defines.PARALLAX = false;
  45170. }
  45171. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45172. }
  45173. else {
  45174. defines.BUMP = false;
  45175. }
  45176. var refractionTexture = this._getRefractionTexture();
  45177. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45178. defines.REFRACTION = true;
  45179. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45180. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45181. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45182. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45183. if (this._linkRefractionWithTransparency) {
  45184. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45185. }
  45186. }
  45187. else {
  45188. defines.REFRACTION = false;
  45189. }
  45190. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45191. defines.ENVIRONMENTBRDF = true;
  45192. }
  45193. else {
  45194. defines.ENVIRONMENTBRDF = false;
  45195. }
  45196. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45197. defines.ALPHAFROMALBEDO = true;
  45198. }
  45199. else {
  45200. defines.ALPHAFROMALBEDO = false;
  45201. }
  45202. }
  45203. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45204. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45205. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45206. if (!this.backFaceCulling && this._twoSidedLighting) {
  45207. defines.TWOSIDEDLIGHTING = true;
  45208. }
  45209. else {
  45210. defines.TWOSIDEDLIGHTING = false;
  45211. }
  45212. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45213. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45214. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45215. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45216. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45217. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45218. }
  45219. if (defines._areImageProcessingDirty) {
  45220. this._imageProcessingConfiguration.prepareDefines(defines);
  45221. }
  45222. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45223. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45224. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45225. // Misc.
  45226. if (defines._areMiscDirty) {
  45227. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45228. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45229. }
  45230. // Values that need to be evaluated on every frame
  45231. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45232. // Attribs
  45233. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45234. };
  45235. /**
  45236. * Force shader compilation
  45237. */
  45238. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45239. var _this = this;
  45240. var localOptions = __assign({ clipPlane: false }, options);
  45241. var defines = new PBRMaterialDefines();
  45242. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45243. if (effect.isReady()) {
  45244. if (onCompiled) {
  45245. onCompiled(this);
  45246. }
  45247. }
  45248. else {
  45249. effect.onCompileObservable.add(function () {
  45250. if (onCompiled) {
  45251. onCompiled(_this);
  45252. }
  45253. });
  45254. }
  45255. };
  45256. /**
  45257. * Initializes the uniform buffer layout for the shader.
  45258. */
  45259. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45260. // Order is important !
  45261. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45262. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45263. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45264. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45265. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45266. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45267. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45268. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45269. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45270. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45271. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45272. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45273. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45274. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45275. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45276. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45277. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45278. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45279. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45280. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45281. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45282. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45283. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45284. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45285. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45286. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45287. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45288. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45289. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45290. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45291. this._uniformBuffer.addUniform("pointSize", 1);
  45292. this._uniformBuffer.create();
  45293. };
  45294. /**
  45295. * Unbinds the textures.
  45296. */
  45297. PBRBaseMaterial.prototype.unbind = function () {
  45298. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45299. this._uniformBuffer.setTexture("reflectionSampler", null);
  45300. }
  45301. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45302. this._uniformBuffer.setTexture("refractionSampler", null);
  45303. }
  45304. _super.prototype.unbind.call(this);
  45305. };
  45306. /**
  45307. * Binds the submesh data.
  45308. * @param world - The world matrix.
  45309. * @param mesh - The BJS mesh.
  45310. * @param subMesh - A submesh of the BJS mesh.
  45311. */
  45312. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45313. var scene = this.getScene();
  45314. var defines = subMesh._materialDefines;
  45315. if (!defines) {
  45316. return;
  45317. }
  45318. var effect = subMesh.effect;
  45319. if (!effect) {
  45320. return;
  45321. }
  45322. this._activeEffect = effect;
  45323. // Matrices
  45324. this.bindOnlyWorldMatrix(world);
  45325. // Normal Matrix
  45326. if (defines.OBJECTSPACE_NORMALMAP) {
  45327. world.toNormalMatrix(this._normalMatrix);
  45328. this.bindOnlyNormalMatrix(this._normalMatrix);
  45329. }
  45330. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45331. // Bones
  45332. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45333. var reflectionTexture = null;
  45334. if (mustRebind) {
  45335. this._uniformBuffer.bindToEffect(effect, "Material");
  45336. this.bindViewProjection(effect);
  45337. reflectionTexture = this._getReflectionTexture();
  45338. var refractionTexture = this._getRefractionTexture();
  45339. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45340. // Texture uniforms
  45341. if (scene.texturesEnabled) {
  45342. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45343. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45344. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45345. }
  45346. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45347. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45348. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45349. }
  45350. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45351. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45352. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45353. }
  45354. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45355. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45356. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45357. if (reflectionTexture.boundingBoxSize) {
  45358. var cubeTexture = reflectionTexture;
  45359. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45360. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45361. }
  45362. var polynomials = reflectionTexture.sphericalPolynomial;
  45363. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45364. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45365. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45366. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45367. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45368. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45369. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45370. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45371. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45372. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45373. }
  45374. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45375. }
  45376. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45377. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45378. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45379. }
  45380. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45381. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45382. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45383. }
  45384. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45385. if (this._metallicTexture) {
  45386. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45387. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45388. }
  45389. else if (this._reflectivityTexture) {
  45390. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45391. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45392. }
  45393. if (this._microSurfaceTexture) {
  45394. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45395. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45396. }
  45397. }
  45398. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45399. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45400. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45401. if (scene._mirroredCameraPosition) {
  45402. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45403. }
  45404. else {
  45405. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45406. }
  45407. }
  45408. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45409. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45410. var depth = 1.0;
  45411. if (!refractionTexture.isCube) {
  45412. if (refractionTexture.depth) {
  45413. depth = refractionTexture.depth;
  45414. }
  45415. }
  45416. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45417. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45418. }
  45419. }
  45420. // Point size
  45421. if (this.pointsCloud) {
  45422. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45423. }
  45424. // Colors
  45425. if (defines.METALLICWORKFLOW) {
  45426. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45427. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45428. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45429. }
  45430. else {
  45431. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45432. }
  45433. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45434. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45435. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45436. // Misc
  45437. this._lightingInfos.x = this._directIntensity;
  45438. this._lightingInfos.y = this._emissiveIntensity;
  45439. this._lightingInfos.z = this._environmentIntensity;
  45440. this._lightingInfos.w = this._specularIntensity;
  45441. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45442. }
  45443. // Textures
  45444. if (scene.texturesEnabled) {
  45445. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45446. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45447. }
  45448. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45449. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45450. }
  45451. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45452. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45453. }
  45454. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45455. if (defines.LODBASEDMICROSFURACE) {
  45456. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45457. }
  45458. else {
  45459. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45460. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45461. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45462. }
  45463. }
  45464. if (defines.ENVIRONMENTBRDF) {
  45465. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45466. }
  45467. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45468. if (defines.LODBASEDMICROSFURACE) {
  45469. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45470. }
  45471. else {
  45472. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45473. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45474. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45475. }
  45476. }
  45477. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45478. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45479. }
  45480. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45481. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45482. }
  45483. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45484. if (this._metallicTexture) {
  45485. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45486. }
  45487. else if (this._reflectivityTexture) {
  45488. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45489. }
  45490. if (this._microSurfaceTexture) {
  45491. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45492. }
  45493. }
  45494. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45495. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45496. }
  45497. }
  45498. // Clip plane
  45499. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45500. // Colors
  45501. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45502. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45503. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45504. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45505. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45506. }
  45507. if (mustRebind || !this.isFrozen) {
  45508. // Lights
  45509. if (scene.lightsEnabled && !this._disableLighting) {
  45510. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45511. }
  45512. // View
  45513. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45514. this.bindView(effect);
  45515. }
  45516. // Fog
  45517. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45518. // Morph targets
  45519. if (defines.NUM_MORPH_INFLUENCERS) {
  45520. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45521. }
  45522. // image processing
  45523. this._imageProcessingConfiguration.bind(this._activeEffect);
  45524. // Log. depth
  45525. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45526. }
  45527. this._uniformBuffer.update();
  45528. this._afterBind(mesh, this._activeEffect);
  45529. };
  45530. /**
  45531. * Returns the animatable textures.
  45532. * @returns - Array of animatable textures.
  45533. */
  45534. PBRBaseMaterial.prototype.getAnimatables = function () {
  45535. var results = [];
  45536. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45537. results.push(this._albedoTexture);
  45538. }
  45539. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45540. results.push(this._ambientTexture);
  45541. }
  45542. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45543. results.push(this._opacityTexture);
  45544. }
  45545. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45546. results.push(this._reflectionTexture);
  45547. }
  45548. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45549. results.push(this._emissiveTexture);
  45550. }
  45551. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45552. results.push(this._metallicTexture);
  45553. }
  45554. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45555. results.push(this._reflectivityTexture);
  45556. }
  45557. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45558. results.push(this._bumpTexture);
  45559. }
  45560. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45561. results.push(this._lightmapTexture);
  45562. }
  45563. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45564. results.push(this._refractionTexture);
  45565. }
  45566. return results;
  45567. };
  45568. /**
  45569. * Returns the texture used for reflections.
  45570. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45571. */
  45572. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45573. if (this._reflectionTexture) {
  45574. return this._reflectionTexture;
  45575. }
  45576. return this.getScene().environmentTexture;
  45577. };
  45578. /**
  45579. * Returns the texture used for refraction or null if none is used.
  45580. * @returns - Refection texture if present. If no refraction texture and refraction
  45581. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45582. */
  45583. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45584. if (this._refractionTexture) {
  45585. return this._refractionTexture;
  45586. }
  45587. if (this._linkRefractionWithTransparency) {
  45588. return this.getScene().environmentTexture;
  45589. }
  45590. return null;
  45591. };
  45592. /**
  45593. * Disposes the resources of the material.
  45594. * @param forceDisposeEffect - Forces the disposal of effects.
  45595. * @param forceDisposeTextures - Forces the disposal of all textures.
  45596. */
  45597. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45598. if (forceDisposeTextures) {
  45599. if (this._albedoTexture) {
  45600. this._albedoTexture.dispose();
  45601. }
  45602. if (this._ambientTexture) {
  45603. this._ambientTexture.dispose();
  45604. }
  45605. if (this._opacityTexture) {
  45606. this._opacityTexture.dispose();
  45607. }
  45608. if (this._reflectionTexture) {
  45609. this._reflectionTexture.dispose();
  45610. }
  45611. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45612. this._environmentBRDFTexture.dispose();
  45613. }
  45614. if (this._emissiveTexture) {
  45615. this._emissiveTexture.dispose();
  45616. }
  45617. if (this._metallicTexture) {
  45618. this._metallicTexture.dispose();
  45619. }
  45620. if (this._reflectivityTexture) {
  45621. this._reflectivityTexture.dispose();
  45622. }
  45623. if (this._bumpTexture) {
  45624. this._bumpTexture.dispose();
  45625. }
  45626. if (this._lightmapTexture) {
  45627. this._lightmapTexture.dispose();
  45628. }
  45629. if (this._refractionTexture) {
  45630. this._refractionTexture.dispose();
  45631. }
  45632. }
  45633. this._renderTargets.dispose();
  45634. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45635. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45636. }
  45637. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45638. };
  45639. /**
  45640. * Stores the reflectivity values based on metallic roughness workflow.
  45641. */
  45642. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45643. __decorate([
  45644. BABYLON.serializeAsImageProcessingConfiguration()
  45645. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45646. __decorate([
  45647. BABYLON.serialize()
  45648. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45649. __decorate([
  45650. BABYLON.serialize()
  45651. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45652. return PBRBaseMaterial;
  45653. }(BABYLON.PushMaterial));
  45654. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45655. })(BABYLON || (BABYLON = {}));
  45656. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45657. var BABYLON;
  45658. (function (BABYLON) {
  45659. /**
  45660. * The Physically based simple base material of BJS.
  45661. *
  45662. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45663. * It is used as the base class for both the specGloss and metalRough conventions.
  45664. */
  45665. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45666. __extends(PBRBaseSimpleMaterial, _super);
  45667. /**
  45668. * Instantiates a new PBRMaterial instance.
  45669. *
  45670. * @param name The material name
  45671. * @param scene The scene the material will be use in.
  45672. */
  45673. function PBRBaseSimpleMaterial(name, scene) {
  45674. var _this = _super.call(this, name, scene) || this;
  45675. /**
  45676. * Number of Simultaneous lights allowed on the material.
  45677. */
  45678. _this.maxSimultaneousLights = 4;
  45679. /**
  45680. * If sets to true, disables all the lights affecting the material.
  45681. */
  45682. _this.disableLighting = false;
  45683. /**
  45684. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45685. */
  45686. _this.invertNormalMapX = false;
  45687. /**
  45688. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45689. */
  45690. _this.invertNormalMapY = false;
  45691. /**
  45692. * Emissivie color used to self-illuminate the model.
  45693. */
  45694. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45695. /**
  45696. * Occlusion Channel Strenght.
  45697. */
  45698. _this.occlusionStrength = 1.0;
  45699. _this.useLightmapAsShadowmap = false;
  45700. _this._useAlphaFromAlbedoTexture = true;
  45701. _this._useAmbientInGrayScale = true;
  45702. return _this;
  45703. }
  45704. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45705. /**
  45706. * Gets the current double sided mode.
  45707. */
  45708. get: function () {
  45709. return this._twoSidedLighting;
  45710. },
  45711. /**
  45712. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45713. */
  45714. set: function (value) {
  45715. if (this._twoSidedLighting === value) {
  45716. return;
  45717. }
  45718. this._twoSidedLighting = value;
  45719. this.backFaceCulling = !value;
  45720. this._markAllSubMeshesAsTexturesDirty();
  45721. },
  45722. enumerable: true,
  45723. configurable: true
  45724. });
  45725. /**
  45726. * Return the active textures of the material.
  45727. */
  45728. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45729. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45730. if (this.environmentTexture) {
  45731. activeTextures.push(this.environmentTexture);
  45732. }
  45733. if (this.normalTexture) {
  45734. activeTextures.push(this.normalTexture);
  45735. }
  45736. if (this.emissiveTexture) {
  45737. activeTextures.push(this.emissiveTexture);
  45738. }
  45739. if (this.occlusionTexture) {
  45740. activeTextures.push(this.occlusionTexture);
  45741. }
  45742. if (this.lightmapTexture) {
  45743. activeTextures.push(this.lightmapTexture);
  45744. }
  45745. return activeTextures;
  45746. };
  45747. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45748. if (_super.prototype.hasTexture.call(this, texture)) {
  45749. return true;
  45750. }
  45751. if (this.lightmapTexture === texture) {
  45752. return true;
  45753. }
  45754. return false;
  45755. };
  45756. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45757. return "PBRBaseSimpleMaterial";
  45758. };
  45759. __decorate([
  45760. BABYLON.serialize(),
  45761. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45762. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45763. __decorate([
  45764. BABYLON.serialize(),
  45765. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45766. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45767. __decorate([
  45768. BABYLON.serializeAsTexture(),
  45769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45770. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45771. __decorate([
  45772. BABYLON.serialize(),
  45773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45774. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45775. __decorate([
  45776. BABYLON.serialize(),
  45777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45778. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45779. __decorate([
  45780. BABYLON.serializeAsTexture(),
  45781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45782. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45783. __decorate([
  45784. BABYLON.serializeAsColor3("emissive"),
  45785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45786. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45787. __decorate([
  45788. BABYLON.serializeAsTexture(),
  45789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45790. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45791. __decorate([
  45792. BABYLON.serialize(),
  45793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45794. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45795. __decorate([
  45796. BABYLON.serializeAsTexture(),
  45797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45798. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45799. __decorate([
  45800. BABYLON.serialize(),
  45801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45802. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45803. __decorate([
  45804. BABYLON.serialize()
  45805. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45806. __decorate([
  45807. BABYLON.serializeAsTexture(),
  45808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45809. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45810. __decorate([
  45811. BABYLON.serialize(),
  45812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45813. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45814. return PBRBaseSimpleMaterial;
  45815. }(BABYLON.PBRBaseMaterial));
  45816. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45817. })(BABYLON || (BABYLON = {}));
  45818. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45819. var BABYLON;
  45820. (function (BABYLON) {
  45821. /**
  45822. * The Physically based material of BJS.
  45823. *
  45824. * This offers the main features of a standard PBR material.
  45825. * For more information, please refer to the documentation :
  45826. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45827. */
  45828. var PBRMaterial = /** @class */ (function (_super) {
  45829. __extends(PBRMaterial, _super);
  45830. /**
  45831. * Instantiates a new PBRMaterial instance.
  45832. *
  45833. * @param name The material name
  45834. * @param scene The scene the material will be use in.
  45835. */
  45836. function PBRMaterial(name, scene) {
  45837. var _this = _super.call(this, name, scene) || this;
  45838. /**
  45839. * Intensity of the direct lights e.g. the four lights available in your scene.
  45840. * This impacts both the direct diffuse and specular highlights.
  45841. */
  45842. _this.directIntensity = 1.0;
  45843. /**
  45844. * Intensity of the emissive part of the material.
  45845. * This helps controlling the emissive effect without modifying the emissive color.
  45846. */
  45847. _this.emissiveIntensity = 1.0;
  45848. /**
  45849. * Intensity of the environment e.g. how much the environment will light the object
  45850. * either through harmonics for rough material or through the refelction for shiny ones.
  45851. */
  45852. _this.environmentIntensity = 1.0;
  45853. /**
  45854. * This is a special control allowing the reduction of the specular highlights coming from the
  45855. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45856. */
  45857. _this.specularIntensity = 1.0;
  45858. /**
  45859. * Debug Control allowing disabling the bump map on this material.
  45860. */
  45861. _this.disableBumpMap = false;
  45862. /**
  45863. * AKA Occlusion Texture Intensity in other nomenclature.
  45864. */
  45865. _this.ambientTextureStrength = 1.0;
  45866. /**
  45867. * The color of a material in ambient lighting.
  45868. */
  45869. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45870. /**
  45871. * AKA Diffuse Color in other nomenclature.
  45872. */
  45873. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45874. /**
  45875. * AKA Specular Color in other nomenclature.
  45876. */
  45877. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45878. /**
  45879. * The color reflected from the material.
  45880. */
  45881. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45882. /**
  45883. * The color emitted from the material.
  45884. */
  45885. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45886. /**
  45887. * AKA Glossiness in other nomenclature.
  45888. */
  45889. _this.microSurface = 1.0;
  45890. /**
  45891. * source material index of refraction (IOR)' / 'destination material IOR.
  45892. */
  45893. _this.indexOfRefraction = 0.66;
  45894. /**
  45895. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45896. */
  45897. _this.invertRefractionY = false;
  45898. /**
  45899. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45900. * Materials half opaque for instance using refraction could benefit from this control.
  45901. */
  45902. _this.linkRefractionWithTransparency = false;
  45903. _this.useLightmapAsShadowmap = false;
  45904. /**
  45905. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45906. */
  45907. _this.useAlphaFromAlbedoTexture = false;
  45908. /**
  45909. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45910. */
  45911. _this.forceAlphaTest = false;
  45912. /**
  45913. * Defines the alpha limits in alpha test mode.
  45914. */
  45915. _this.alphaCutOff = 0.4;
  45916. /**
  45917. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45918. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45919. */
  45920. _this.useSpecularOverAlpha = true;
  45921. /**
  45922. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45923. */
  45924. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45925. /**
  45926. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45927. */
  45928. _this.useRoughnessFromMetallicTextureAlpha = true;
  45929. /**
  45930. * Specifies if the metallic texture contains the roughness information in its green channel.
  45931. */
  45932. _this.useRoughnessFromMetallicTextureGreen = false;
  45933. /**
  45934. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45935. */
  45936. _this.useMetallnessFromMetallicTextureBlue = false;
  45937. /**
  45938. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45939. */
  45940. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45941. /**
  45942. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45943. */
  45944. _this.useAmbientInGrayScale = false;
  45945. /**
  45946. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45947. * The material will try to infer what glossiness each pixel should be.
  45948. */
  45949. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45950. /**
  45951. * BJS is using an harcoded light falloff based on a manually sets up range.
  45952. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45953. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45954. */
  45955. _this.usePhysicalLightFalloff = true;
  45956. /**
  45957. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45958. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45959. */
  45960. _this.useRadianceOverAlpha = true;
  45961. /**
  45962. * Allows using an object space normal map (instead of tangent space).
  45963. */
  45964. _this.useObjectSpaceNormalMap = false;
  45965. /**
  45966. * Allows using the bump map in parallax mode.
  45967. */
  45968. _this.useParallax = false;
  45969. /**
  45970. * Allows using the bump map in parallax occlusion mode.
  45971. */
  45972. _this.useParallaxOcclusion = false;
  45973. /**
  45974. * Controls the scale bias of the parallax mode.
  45975. */
  45976. _this.parallaxScaleBias = 0.05;
  45977. /**
  45978. * If sets to true, disables all the lights affecting the material.
  45979. */
  45980. _this.disableLighting = false;
  45981. /**
  45982. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45983. */
  45984. _this.forceIrradianceInFragment = false;
  45985. /**
  45986. * Number of Simultaneous lights allowed on the material.
  45987. */
  45988. _this.maxSimultaneousLights = 4;
  45989. /**
  45990. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45991. */
  45992. _this.invertNormalMapX = false;
  45993. /**
  45994. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45995. */
  45996. _this.invertNormalMapY = false;
  45997. /**
  45998. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45999. */
  46000. _this.twoSidedLighting = false;
  46001. /**
  46002. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46003. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46004. */
  46005. _this.useAlphaFresnel = false;
  46006. /**
  46007. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46008. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46009. */
  46010. _this.useLinearAlphaFresnel = false;
  46011. /**
  46012. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46013. * And/Or occlude the blended part.
  46014. */
  46015. _this.environmentBRDFTexture = null;
  46016. /**
  46017. * Force normal to face away from face.
  46018. */
  46019. _this.forceNormalForward = false;
  46020. /**
  46021. * Enables specular anti aliasing in the PBR shader.
  46022. * It will both interacts on the Geometry for analytical and IBL lighting.
  46023. * It also prefilter the roughness map based on the bump values.
  46024. */
  46025. _this.enableSpecularAntiAliasing = false;
  46026. /**
  46027. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46028. * makes the reflect vector face the model (under horizon).
  46029. */
  46030. _this.useHorizonOcclusion = true;
  46031. /**
  46032. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46033. * too much the area relying on ambient texture to define their ambient occlusion.
  46034. */
  46035. _this.useRadianceOcclusion = true;
  46036. /**
  46037. * If set to true, no lighting calculations will be applied.
  46038. */
  46039. _this.unlit = false;
  46040. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46041. return _this;
  46042. }
  46043. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46044. /**
  46045. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46046. */
  46047. get: function () {
  46048. return this._PBRMATERIAL_OPAQUE;
  46049. },
  46050. enumerable: true,
  46051. configurable: true
  46052. });
  46053. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46054. /**
  46055. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46056. */
  46057. get: function () {
  46058. return this._PBRMATERIAL_ALPHATEST;
  46059. },
  46060. enumerable: true,
  46061. configurable: true
  46062. });
  46063. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46064. /**
  46065. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46066. */
  46067. get: function () {
  46068. return this._PBRMATERIAL_ALPHABLEND;
  46069. },
  46070. enumerable: true,
  46071. configurable: true
  46072. });
  46073. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46074. /**
  46075. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46076. * They are also discarded below the alpha cutoff threshold to improve performances.
  46077. */
  46078. get: function () {
  46079. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46080. },
  46081. enumerable: true,
  46082. configurable: true
  46083. });
  46084. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46085. /**
  46086. * Gets the image processing configuration used either in this material.
  46087. */
  46088. get: function () {
  46089. return this._imageProcessingConfiguration;
  46090. },
  46091. /**
  46092. * Sets the Default image processing configuration used either in the this material.
  46093. *
  46094. * If sets to null, the scene one is in use.
  46095. */
  46096. set: function (value) {
  46097. this._attachImageProcessingConfiguration(value);
  46098. // Ensure the effect will be rebuilt.
  46099. this._markAllSubMeshesAsTexturesDirty();
  46100. },
  46101. enumerable: true,
  46102. configurable: true
  46103. });
  46104. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46105. /**
  46106. * Gets wether the color curves effect is enabled.
  46107. */
  46108. get: function () {
  46109. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46110. },
  46111. /**
  46112. * Sets wether the color curves effect is enabled.
  46113. */
  46114. set: function (value) {
  46115. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46116. },
  46117. enumerable: true,
  46118. configurable: true
  46119. });
  46120. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46121. /**
  46122. * Gets wether the color grading effect is enabled.
  46123. */
  46124. get: function () {
  46125. return this.imageProcessingConfiguration.colorGradingEnabled;
  46126. },
  46127. /**
  46128. * Gets wether the color grading effect is enabled.
  46129. */
  46130. set: function (value) {
  46131. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46132. },
  46133. enumerable: true,
  46134. configurable: true
  46135. });
  46136. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46137. /**
  46138. * Gets wether tonemapping is enabled or not.
  46139. */
  46140. get: function () {
  46141. return this._imageProcessingConfiguration.toneMappingEnabled;
  46142. },
  46143. /**
  46144. * Sets wether tonemapping is enabled or not
  46145. */
  46146. set: function (value) {
  46147. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46148. },
  46149. enumerable: true,
  46150. configurable: true
  46151. });
  46152. ;
  46153. ;
  46154. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46155. /**
  46156. * The camera exposure used on this material.
  46157. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46158. * This corresponds to a photographic exposure.
  46159. */
  46160. get: function () {
  46161. return this._imageProcessingConfiguration.exposure;
  46162. },
  46163. /**
  46164. * The camera exposure used on this material.
  46165. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46166. * This corresponds to a photographic exposure.
  46167. */
  46168. set: function (value) {
  46169. this._imageProcessingConfiguration.exposure = value;
  46170. },
  46171. enumerable: true,
  46172. configurable: true
  46173. });
  46174. ;
  46175. ;
  46176. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46177. /**
  46178. * Gets The camera contrast used on this material.
  46179. */
  46180. get: function () {
  46181. return this._imageProcessingConfiguration.contrast;
  46182. },
  46183. /**
  46184. * Sets The camera contrast used on this material.
  46185. */
  46186. set: function (value) {
  46187. this._imageProcessingConfiguration.contrast = value;
  46188. },
  46189. enumerable: true,
  46190. configurable: true
  46191. });
  46192. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46193. /**
  46194. * Gets the Color Grading 2D Lookup Texture.
  46195. */
  46196. get: function () {
  46197. return this._imageProcessingConfiguration.colorGradingTexture;
  46198. },
  46199. /**
  46200. * Sets the Color Grading 2D Lookup Texture.
  46201. */
  46202. set: function (value) {
  46203. this._imageProcessingConfiguration.colorGradingTexture = value;
  46204. },
  46205. enumerable: true,
  46206. configurable: true
  46207. });
  46208. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46209. /**
  46210. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46211. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46212. * 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;
  46213. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46214. */
  46215. get: function () {
  46216. return this._imageProcessingConfiguration.colorCurves;
  46217. },
  46218. /**
  46219. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46220. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46221. * 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;
  46222. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46223. */
  46224. set: function (value) {
  46225. this._imageProcessingConfiguration.colorCurves = value;
  46226. },
  46227. enumerable: true,
  46228. configurable: true
  46229. });
  46230. /**
  46231. * Returns the name of this material class.
  46232. */
  46233. PBRMaterial.prototype.getClassName = function () {
  46234. return "PBRMaterial";
  46235. };
  46236. /**
  46237. * Returns an array of the actively used textures.
  46238. * @returns - Array of BaseTextures
  46239. */
  46240. PBRMaterial.prototype.getActiveTextures = function () {
  46241. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46242. if (this._albedoTexture) {
  46243. activeTextures.push(this._albedoTexture);
  46244. }
  46245. if (this._ambientTexture) {
  46246. activeTextures.push(this._ambientTexture);
  46247. }
  46248. if (this._opacityTexture) {
  46249. activeTextures.push(this._opacityTexture);
  46250. }
  46251. if (this._reflectionTexture) {
  46252. activeTextures.push(this._reflectionTexture);
  46253. }
  46254. if (this._emissiveTexture) {
  46255. activeTextures.push(this._emissiveTexture);
  46256. }
  46257. if (this._reflectivityTexture) {
  46258. activeTextures.push(this._reflectivityTexture);
  46259. }
  46260. if (this._metallicTexture) {
  46261. activeTextures.push(this._metallicTexture);
  46262. }
  46263. if (this._microSurfaceTexture) {
  46264. activeTextures.push(this._microSurfaceTexture);
  46265. }
  46266. if (this._bumpTexture) {
  46267. activeTextures.push(this._bumpTexture);
  46268. }
  46269. if (this._lightmapTexture) {
  46270. activeTextures.push(this._lightmapTexture);
  46271. }
  46272. if (this._refractionTexture) {
  46273. activeTextures.push(this._refractionTexture);
  46274. }
  46275. return activeTextures;
  46276. };
  46277. /**
  46278. * Checks to see if a texture is used in the material.
  46279. * @param texture - Base texture to use.
  46280. * @returns - Boolean specifying if a texture is used in the material.
  46281. */
  46282. PBRMaterial.prototype.hasTexture = function (texture) {
  46283. if (_super.prototype.hasTexture.call(this, texture)) {
  46284. return true;
  46285. }
  46286. if (this._albedoTexture === texture) {
  46287. return true;
  46288. }
  46289. if (this._ambientTexture === texture) {
  46290. return true;
  46291. }
  46292. if (this._opacityTexture === texture) {
  46293. return true;
  46294. }
  46295. if (this._reflectionTexture === texture) {
  46296. return true;
  46297. }
  46298. if (this._reflectivityTexture === texture) {
  46299. return true;
  46300. }
  46301. if (this._metallicTexture === texture) {
  46302. return true;
  46303. }
  46304. if (this._microSurfaceTexture === texture) {
  46305. return true;
  46306. }
  46307. if (this._bumpTexture === texture) {
  46308. return true;
  46309. }
  46310. if (this._lightmapTexture === texture) {
  46311. return true;
  46312. }
  46313. if (this._refractionTexture === texture) {
  46314. return true;
  46315. }
  46316. return false;
  46317. };
  46318. /**
  46319. * Makes a duplicate of the current material.
  46320. * @param name - name to use for the new material.
  46321. */
  46322. PBRMaterial.prototype.clone = function (name) {
  46323. var _this = this;
  46324. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46325. clone.id = name;
  46326. clone.name = name;
  46327. return clone;
  46328. };
  46329. /**
  46330. * Serializes this PBR Material.
  46331. * @returns - An object with the serialized material.
  46332. */
  46333. PBRMaterial.prototype.serialize = function () {
  46334. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46335. serializationObject.customType = "BABYLON.PBRMaterial";
  46336. return serializationObject;
  46337. };
  46338. // Statics
  46339. /**
  46340. * Parses a PBR Material from a serialized object.
  46341. * @param source - Serialized object.
  46342. * @param scene - BJS scene instance.
  46343. * @param rootUrl - url for the scene object
  46344. * @returns - PBRMaterial
  46345. */
  46346. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46347. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46348. };
  46349. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46350. /**
  46351. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46352. */
  46353. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46354. /**
  46355. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46356. */
  46357. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46358. /**
  46359. * 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.
  46360. * They are also discarded below the alpha cutoff threshold to improve performances.
  46361. */
  46362. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46363. __decorate([
  46364. BABYLON.serialize(),
  46365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46366. ], PBRMaterial.prototype, "directIntensity", void 0);
  46367. __decorate([
  46368. BABYLON.serialize(),
  46369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46370. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46371. __decorate([
  46372. BABYLON.serialize(),
  46373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46374. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46375. __decorate([
  46376. BABYLON.serialize(),
  46377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46378. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46379. __decorate([
  46380. BABYLON.serialize(),
  46381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46382. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46383. __decorate([
  46384. BABYLON.serializeAsTexture(),
  46385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46386. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46387. __decorate([
  46388. BABYLON.serializeAsTexture(),
  46389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46390. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46391. __decorate([
  46392. BABYLON.serialize(),
  46393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46394. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46395. __decorate([
  46396. BABYLON.serializeAsTexture(),
  46397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46398. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46399. __decorate([
  46400. BABYLON.serializeAsTexture(),
  46401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46402. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46403. __decorate([
  46404. BABYLON.serializeAsTexture(),
  46405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46406. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46407. __decorate([
  46408. BABYLON.serializeAsTexture(),
  46409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46410. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46411. __decorate([
  46412. BABYLON.serializeAsTexture(),
  46413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46414. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46415. __decorate([
  46416. BABYLON.serialize(),
  46417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46418. ], PBRMaterial.prototype, "metallic", void 0);
  46419. __decorate([
  46420. BABYLON.serialize(),
  46421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46422. ], PBRMaterial.prototype, "roughness", void 0);
  46423. __decorate([
  46424. BABYLON.serializeAsTexture(),
  46425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46426. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46427. __decorate([
  46428. BABYLON.serializeAsTexture(),
  46429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46430. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46431. __decorate([
  46432. BABYLON.serializeAsTexture(),
  46433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46434. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46435. __decorate([
  46436. BABYLON.serializeAsTexture(),
  46437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46438. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46439. __decorate([
  46440. BABYLON.serializeAsColor3("ambient"),
  46441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46442. ], PBRMaterial.prototype, "ambientColor", void 0);
  46443. __decorate([
  46444. BABYLON.serializeAsColor3("albedo"),
  46445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46446. ], PBRMaterial.prototype, "albedoColor", void 0);
  46447. __decorate([
  46448. BABYLON.serializeAsColor3("reflectivity"),
  46449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46450. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46451. __decorate([
  46452. BABYLON.serializeAsColor3("reflection"),
  46453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46454. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46455. __decorate([
  46456. BABYLON.serializeAsColor3("emissive"),
  46457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46458. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46459. __decorate([
  46460. BABYLON.serialize(),
  46461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46462. ], PBRMaterial.prototype, "microSurface", void 0);
  46463. __decorate([
  46464. BABYLON.serialize(),
  46465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46466. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46467. __decorate([
  46468. BABYLON.serialize(),
  46469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46470. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46471. __decorate([
  46472. BABYLON.serialize(),
  46473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46474. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46475. __decorate([
  46476. BABYLON.serialize(),
  46477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46478. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46479. __decorate([
  46480. BABYLON.serialize(),
  46481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46482. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46483. __decorate([
  46484. BABYLON.serialize(),
  46485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46486. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46487. __decorate([
  46488. BABYLON.serialize(),
  46489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46490. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46491. __decorate([
  46492. BABYLON.serialize(),
  46493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46494. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46495. __decorate([
  46496. BABYLON.serialize(),
  46497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46498. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46499. __decorate([
  46500. BABYLON.serialize(),
  46501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46502. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46503. __decorate([
  46504. BABYLON.serialize(),
  46505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46506. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46507. __decorate([
  46508. BABYLON.serialize(),
  46509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46510. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46511. __decorate([
  46512. BABYLON.serialize(),
  46513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46514. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46515. __decorate([
  46516. BABYLON.serialize(),
  46517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46518. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46519. __decorate([
  46520. BABYLON.serialize(),
  46521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46522. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46523. __decorate([
  46524. BABYLON.serialize(),
  46525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46526. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46527. __decorate([
  46528. BABYLON.serialize(),
  46529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46530. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46531. __decorate([
  46532. BABYLON.serialize(),
  46533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46534. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46535. __decorate([
  46536. BABYLON.serialize(),
  46537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46538. ], PBRMaterial.prototype, "useParallax", void 0);
  46539. __decorate([
  46540. BABYLON.serialize(),
  46541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46542. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46543. __decorate([
  46544. BABYLON.serialize(),
  46545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46546. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46547. __decorate([
  46548. BABYLON.serialize(),
  46549. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46550. ], PBRMaterial.prototype, "disableLighting", void 0);
  46551. __decorate([
  46552. BABYLON.serialize(),
  46553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46554. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46555. __decorate([
  46556. BABYLON.serialize(),
  46557. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46558. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46559. __decorate([
  46560. BABYLON.serialize(),
  46561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46562. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46563. __decorate([
  46564. BABYLON.serialize(),
  46565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46566. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46567. __decorate([
  46568. BABYLON.serialize(),
  46569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46570. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46571. __decorate([
  46572. BABYLON.serialize(),
  46573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46574. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46575. __decorate([
  46576. BABYLON.serialize(),
  46577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46578. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46579. __decorate([
  46580. BABYLON.serializeAsTexture(),
  46581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46582. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46583. __decorate([
  46584. BABYLON.serialize(),
  46585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46586. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46587. __decorate([
  46588. BABYLON.serialize(),
  46589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46590. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46591. __decorate([
  46592. BABYLON.serialize(),
  46593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46594. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46595. __decorate([
  46596. BABYLON.serialize(),
  46597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46598. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46599. __decorate([
  46600. BABYLON.serialize(),
  46601. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46602. ], PBRMaterial.prototype, "unlit", void 0);
  46603. return PBRMaterial;
  46604. }(BABYLON.PBRBaseMaterial));
  46605. BABYLON.PBRMaterial = PBRMaterial;
  46606. })(BABYLON || (BABYLON = {}));
  46607. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46608. var BABYLON;
  46609. (function (BABYLON) {
  46610. /**
  46611. * The PBR material of BJS following the metal roughness convention.
  46612. *
  46613. * This fits to the PBR convention in the GLTF definition:
  46614. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46615. */
  46616. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46617. __extends(PBRMetallicRoughnessMaterial, _super);
  46618. /**
  46619. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46620. *
  46621. * @param name The material name
  46622. * @param scene The scene the material will be use in.
  46623. */
  46624. function PBRMetallicRoughnessMaterial(name, scene) {
  46625. var _this = _super.call(this, name, scene) || this;
  46626. _this._useRoughnessFromMetallicTextureAlpha = false;
  46627. _this._useRoughnessFromMetallicTextureGreen = true;
  46628. _this._useMetallnessFromMetallicTextureBlue = true;
  46629. _this.metallic = 1.0;
  46630. _this.roughness = 1.0;
  46631. return _this;
  46632. }
  46633. /**
  46634. * Return the currrent class name of the material.
  46635. */
  46636. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46637. return "PBRMetallicRoughnessMaterial";
  46638. };
  46639. /**
  46640. * Return the active textures of the material.
  46641. */
  46642. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46643. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46644. if (this.baseTexture) {
  46645. activeTextures.push(this.baseTexture);
  46646. }
  46647. if (this.metallicRoughnessTexture) {
  46648. activeTextures.push(this.metallicRoughnessTexture);
  46649. }
  46650. return activeTextures;
  46651. };
  46652. /**
  46653. * Checks to see if a texture is used in the material.
  46654. * @param texture - Base texture to use.
  46655. * @returns - Boolean specifying if a texture is used in the material.
  46656. */
  46657. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46658. if (_super.prototype.hasTexture.call(this, texture)) {
  46659. return true;
  46660. }
  46661. if (this.baseTexture === texture) {
  46662. return true;
  46663. }
  46664. if (this.metallicRoughnessTexture === texture) {
  46665. return true;
  46666. }
  46667. return false;
  46668. };
  46669. /**
  46670. * Makes a duplicate of the current material.
  46671. * @param name - name to use for the new material.
  46672. */
  46673. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46674. var _this = this;
  46675. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46676. clone.id = name;
  46677. clone.name = name;
  46678. return clone;
  46679. };
  46680. /**
  46681. * Serialize the material to a parsable JSON object.
  46682. */
  46683. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46684. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46685. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46686. return serializationObject;
  46687. };
  46688. /**
  46689. * Parses a JSON object correponding to the serialize function.
  46690. */
  46691. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46692. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46693. };
  46694. __decorate([
  46695. BABYLON.serializeAsColor3(),
  46696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46697. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46698. __decorate([
  46699. BABYLON.serializeAsTexture(),
  46700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46701. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46702. __decorate([
  46703. BABYLON.serialize(),
  46704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46705. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46706. __decorate([
  46707. BABYLON.serialize(),
  46708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46709. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46710. __decorate([
  46711. BABYLON.serializeAsTexture(),
  46712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46713. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46714. return PBRMetallicRoughnessMaterial;
  46715. }(BABYLON.PBRBaseSimpleMaterial));
  46716. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46717. })(BABYLON || (BABYLON = {}));
  46718. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46719. var BABYLON;
  46720. (function (BABYLON) {
  46721. /**
  46722. * The PBR material of BJS following the specular glossiness convention.
  46723. *
  46724. * This fits to the PBR convention in the GLTF definition:
  46725. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46726. */
  46727. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46728. __extends(PBRSpecularGlossinessMaterial, _super);
  46729. /**
  46730. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46731. *
  46732. * @param name The material name
  46733. * @param scene The scene the material will be use in.
  46734. */
  46735. function PBRSpecularGlossinessMaterial(name, scene) {
  46736. var _this = _super.call(this, name, scene) || this;
  46737. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46738. return _this;
  46739. }
  46740. /**
  46741. * Return the currrent class name of the material.
  46742. */
  46743. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46744. return "PBRSpecularGlossinessMaterial";
  46745. };
  46746. /**
  46747. * Return the active textures of the material.
  46748. */
  46749. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46750. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46751. if (this.diffuseTexture) {
  46752. activeTextures.push(this.diffuseTexture);
  46753. }
  46754. if (this.specularGlossinessTexture) {
  46755. activeTextures.push(this.specularGlossinessTexture);
  46756. }
  46757. return activeTextures;
  46758. };
  46759. /**
  46760. * Checks to see if a texture is used in the material.
  46761. * @param texture - Base texture to use.
  46762. * @returns - Boolean specifying if a texture is used in the material.
  46763. */
  46764. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46765. if (_super.prototype.hasTexture.call(this, texture)) {
  46766. return true;
  46767. }
  46768. if (this.diffuseTexture === texture) {
  46769. return true;
  46770. }
  46771. if (this.specularGlossinessTexture === texture) {
  46772. return true;
  46773. }
  46774. return false;
  46775. };
  46776. /**
  46777. * Makes a duplicate of the current material.
  46778. * @param name - name to use for the new material.
  46779. */
  46780. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46781. var _this = this;
  46782. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46783. clone.id = name;
  46784. clone.name = name;
  46785. return clone;
  46786. };
  46787. /**
  46788. * Serialize the material to a parsable JSON object.
  46789. */
  46790. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46791. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46792. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46793. return serializationObject;
  46794. };
  46795. /**
  46796. * Parses a JSON object correponding to the serialize function.
  46797. */
  46798. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46799. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46800. };
  46801. __decorate([
  46802. BABYLON.serializeAsColor3("diffuse"),
  46803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46804. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46805. __decorate([
  46806. BABYLON.serializeAsTexture(),
  46807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46808. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46809. __decorate([
  46810. BABYLON.serializeAsColor3("specular"),
  46811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46812. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46813. __decorate([
  46814. BABYLON.serialize(),
  46815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46816. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46817. __decorate([
  46818. BABYLON.serializeAsTexture(),
  46819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46820. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46821. return PBRSpecularGlossinessMaterial;
  46822. }(BABYLON.PBRBaseSimpleMaterial));
  46823. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46824. })(BABYLON || (BABYLON = {}));
  46825. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46826. var BABYLON;
  46827. (function (BABYLON) {
  46828. BABYLON.CameraInputTypes = {};
  46829. var CameraInputsManager = /** @class */ (function () {
  46830. function CameraInputsManager(camera) {
  46831. this.attached = {};
  46832. this.camera = camera;
  46833. this.checkInputs = function () { };
  46834. }
  46835. /**
  46836. * Add an input method to a camera.
  46837. * builtin inputs example: camera.inputs.addGamepad();
  46838. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46839. * @param input camera input method
  46840. */
  46841. CameraInputsManager.prototype.add = function (input) {
  46842. var type = input.getSimpleName();
  46843. if (this.attached[type]) {
  46844. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46845. return;
  46846. }
  46847. this.attached[type] = input;
  46848. input.camera = this.camera;
  46849. //for checkInputs, we are dynamically creating a function
  46850. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46851. if (input.checkInputs) {
  46852. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46853. }
  46854. if (this.attachedElement) {
  46855. input.attachControl(this.attachedElement);
  46856. }
  46857. };
  46858. /**
  46859. * Remove a specific input method from a camera
  46860. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46861. * @param inputToRemove camera input method
  46862. */
  46863. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46864. for (var cam in this.attached) {
  46865. var input = this.attached[cam];
  46866. if (input === inputToRemove) {
  46867. input.detachControl(this.attachedElement);
  46868. input.camera = null;
  46869. delete this.attached[cam];
  46870. this.rebuildInputCheck();
  46871. }
  46872. }
  46873. };
  46874. CameraInputsManager.prototype.removeByType = function (inputType) {
  46875. for (var cam in this.attached) {
  46876. var input = this.attached[cam];
  46877. if (input.getClassName() === inputType) {
  46878. input.detachControl(this.attachedElement);
  46879. input.camera = null;
  46880. delete this.attached[cam];
  46881. this.rebuildInputCheck();
  46882. }
  46883. }
  46884. };
  46885. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46886. var current = this.checkInputs;
  46887. return function () {
  46888. current();
  46889. fn();
  46890. };
  46891. };
  46892. CameraInputsManager.prototype.attachInput = function (input) {
  46893. if (this.attachedElement) {
  46894. input.attachControl(this.attachedElement, this.noPreventDefault);
  46895. }
  46896. };
  46897. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46898. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46899. if (this.attachedElement) {
  46900. return;
  46901. }
  46902. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46903. this.attachedElement = element;
  46904. this.noPreventDefault = noPreventDefault;
  46905. for (var cam in this.attached) {
  46906. this.attached[cam].attachControl(element, noPreventDefault);
  46907. }
  46908. };
  46909. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46910. if (disconnect === void 0) { disconnect = false; }
  46911. if (this.attachedElement !== element) {
  46912. return;
  46913. }
  46914. for (var cam in this.attached) {
  46915. this.attached[cam].detachControl(element);
  46916. if (disconnect) {
  46917. this.attached[cam].camera = null;
  46918. }
  46919. }
  46920. this.attachedElement = null;
  46921. };
  46922. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46923. this.checkInputs = function () { };
  46924. for (var cam in this.attached) {
  46925. var input = this.attached[cam];
  46926. if (input.checkInputs) {
  46927. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46928. }
  46929. }
  46930. };
  46931. /**
  46932. * Remove all attached input methods from a camera
  46933. */
  46934. CameraInputsManager.prototype.clear = function () {
  46935. if (this.attachedElement) {
  46936. this.detachElement(this.attachedElement, true);
  46937. }
  46938. this.attached = {};
  46939. this.attachedElement = null;
  46940. this.checkInputs = function () { };
  46941. };
  46942. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46943. var inputs = {};
  46944. for (var cam in this.attached) {
  46945. var input = this.attached[cam];
  46946. var res = BABYLON.SerializationHelper.Serialize(input);
  46947. inputs[input.getClassName()] = res;
  46948. }
  46949. serializedCamera.inputsmgr = inputs;
  46950. };
  46951. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46952. var parsedInputs = parsedCamera.inputsmgr;
  46953. if (parsedInputs) {
  46954. this.clear();
  46955. for (var n in parsedInputs) {
  46956. var construct = BABYLON.CameraInputTypes[n];
  46957. if (construct) {
  46958. var parsedinput = parsedInputs[n];
  46959. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46960. this.add(input);
  46961. }
  46962. }
  46963. }
  46964. else {
  46965. //2016-03-08 this part is for managing backward compatibility
  46966. for (var n in this.attached) {
  46967. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46968. if (construct) {
  46969. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46970. this.remove(this.attached[n]);
  46971. this.add(input);
  46972. }
  46973. }
  46974. }
  46975. };
  46976. return CameraInputsManager;
  46977. }());
  46978. BABYLON.CameraInputsManager = CameraInputsManager;
  46979. })(BABYLON || (BABYLON = {}));
  46980. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46981. var BABYLON;
  46982. (function (BABYLON) {
  46983. var TargetCamera = /** @class */ (function (_super) {
  46984. __extends(TargetCamera, _super);
  46985. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46986. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46987. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46988. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46989. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46990. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46991. _this.speed = 2.0;
  46992. _this.noRotationConstraint = false;
  46993. _this.lockedTarget = null;
  46994. _this._currentTarget = BABYLON.Vector3.Zero();
  46995. _this._viewMatrix = BABYLON.Matrix.Zero();
  46996. _this._camMatrix = BABYLON.Matrix.Zero();
  46997. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46998. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46999. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47000. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47001. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47002. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47003. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47004. return _this;
  47005. }
  47006. TargetCamera.prototype.getFrontPosition = function (distance) {
  47007. this.getWorldMatrix();
  47008. var direction = this.getTarget().subtract(this.position);
  47009. direction.normalize();
  47010. direction.scaleInPlace(distance);
  47011. return this.globalPosition.add(direction);
  47012. };
  47013. TargetCamera.prototype._getLockedTargetPosition = function () {
  47014. if (!this.lockedTarget) {
  47015. return null;
  47016. }
  47017. if (this.lockedTarget.absolutePosition) {
  47018. this.lockedTarget.computeWorldMatrix();
  47019. }
  47020. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47021. };
  47022. TargetCamera.prototype.storeState = function () {
  47023. this._storedPosition = this.position.clone();
  47024. this._storedRotation = this.rotation.clone();
  47025. if (this.rotationQuaternion) {
  47026. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47027. }
  47028. return _super.prototype.storeState.call(this);
  47029. };
  47030. /**
  47031. * Restored camera state. You must call storeState() first
  47032. */
  47033. TargetCamera.prototype._restoreStateValues = function () {
  47034. if (!_super.prototype._restoreStateValues.call(this)) {
  47035. return false;
  47036. }
  47037. this.position = this._storedPosition.clone();
  47038. this.rotation = this._storedRotation.clone();
  47039. if (this.rotationQuaternion) {
  47040. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47041. }
  47042. this.cameraDirection.copyFromFloats(0, 0, 0);
  47043. this.cameraRotation.copyFromFloats(0, 0);
  47044. return true;
  47045. };
  47046. // Cache
  47047. TargetCamera.prototype._initCache = function () {
  47048. _super.prototype._initCache.call(this);
  47049. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47050. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47051. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47052. };
  47053. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47054. if (!ignoreParentClass) {
  47055. _super.prototype._updateCache.call(this);
  47056. }
  47057. var lockedTargetPosition = this._getLockedTargetPosition();
  47058. if (!lockedTargetPosition) {
  47059. this._cache.lockedTarget = null;
  47060. }
  47061. else {
  47062. if (!this._cache.lockedTarget) {
  47063. this._cache.lockedTarget = lockedTargetPosition.clone();
  47064. }
  47065. else {
  47066. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47067. }
  47068. }
  47069. this._cache.rotation.copyFrom(this.rotation);
  47070. if (this.rotationQuaternion)
  47071. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47072. };
  47073. // Synchronized
  47074. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47075. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47076. return false;
  47077. }
  47078. var lockedTargetPosition = this._getLockedTargetPosition();
  47079. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47080. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47081. };
  47082. // Methods
  47083. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47084. var engine = this.getEngine();
  47085. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47086. };
  47087. // Target
  47088. TargetCamera.prototype.setTarget = function (target) {
  47089. this.upVector.normalize();
  47090. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47091. this._camMatrix.invert();
  47092. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47093. var vDir = target.subtract(this.position);
  47094. if (vDir.x >= 0.0) {
  47095. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47096. }
  47097. else {
  47098. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47099. }
  47100. this.rotation.z = 0;
  47101. if (isNaN(this.rotation.x)) {
  47102. this.rotation.x = 0;
  47103. }
  47104. if (isNaN(this.rotation.y)) {
  47105. this.rotation.y = 0;
  47106. }
  47107. if (isNaN(this.rotation.z)) {
  47108. this.rotation.z = 0;
  47109. }
  47110. if (this.rotationQuaternion) {
  47111. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47112. }
  47113. };
  47114. /**
  47115. * Return the current target position of the camera. This value is expressed in local space.
  47116. */
  47117. TargetCamera.prototype.getTarget = function () {
  47118. return this._currentTarget;
  47119. };
  47120. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47121. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47122. };
  47123. TargetCamera.prototype._updatePosition = function () {
  47124. if (this.parent) {
  47125. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47126. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47127. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47128. return;
  47129. }
  47130. this.position.addInPlace(this.cameraDirection);
  47131. };
  47132. TargetCamera.prototype._checkInputs = function () {
  47133. var needToMove = this._decideIfNeedsToMove();
  47134. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47135. // Move
  47136. if (needToMove) {
  47137. this._updatePosition();
  47138. }
  47139. // Rotate
  47140. if (needToRotate) {
  47141. this.rotation.x += this.cameraRotation.x;
  47142. this.rotation.y += this.cameraRotation.y;
  47143. //rotate, if quaternion is set and rotation was used
  47144. if (this.rotationQuaternion) {
  47145. var len = this.rotation.lengthSquared();
  47146. if (len) {
  47147. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47148. }
  47149. }
  47150. if (!this.noRotationConstraint) {
  47151. var limit = (Math.PI / 2) * 0.95;
  47152. if (this.rotation.x > limit)
  47153. this.rotation.x = limit;
  47154. if (this.rotation.x < -limit)
  47155. this.rotation.x = -limit;
  47156. }
  47157. }
  47158. // Inertia
  47159. if (needToMove) {
  47160. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47161. this.cameraDirection.x = 0;
  47162. }
  47163. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47164. this.cameraDirection.y = 0;
  47165. }
  47166. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47167. this.cameraDirection.z = 0;
  47168. }
  47169. this.cameraDirection.scaleInPlace(this.inertia);
  47170. }
  47171. if (needToRotate) {
  47172. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47173. this.cameraRotation.x = 0;
  47174. }
  47175. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47176. this.cameraRotation.y = 0;
  47177. }
  47178. this.cameraRotation.scaleInPlace(this.inertia);
  47179. }
  47180. _super.prototype._checkInputs.call(this);
  47181. };
  47182. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47183. if (this.rotationQuaternion) {
  47184. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47185. }
  47186. else {
  47187. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47188. }
  47189. //update the up vector!
  47190. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47191. };
  47192. TargetCamera.prototype._getViewMatrix = function () {
  47193. if (this.lockedTarget) {
  47194. this.setTarget(this._getLockedTargetPosition());
  47195. }
  47196. // Compute
  47197. this._updateCameraRotationMatrix();
  47198. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47199. // Computing target and final matrix
  47200. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47201. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47202. return this._viewMatrix;
  47203. };
  47204. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47205. if (this.parent) {
  47206. var parentWorldMatrix = this.parent.getWorldMatrix();
  47207. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47208. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47209. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47210. this._markSyncedWithParent();
  47211. }
  47212. else {
  47213. this._globalPosition.copyFrom(this.position);
  47214. this._globalCurrentTarget.copyFrom(target);
  47215. this._globalCurrentUpVector.copyFrom(up);
  47216. }
  47217. if (this.getScene().useRightHandedSystem) {
  47218. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47219. }
  47220. else {
  47221. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47222. }
  47223. };
  47224. /**
  47225. * @override
  47226. * Override Camera.createRigCamera
  47227. */
  47228. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47229. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47230. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47231. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47232. if (!this.rotationQuaternion) {
  47233. this.rotationQuaternion = new BABYLON.Quaternion();
  47234. }
  47235. rigCamera._cameraRigParams = {};
  47236. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47237. }
  47238. return rigCamera;
  47239. }
  47240. return null;
  47241. };
  47242. /**
  47243. * @override
  47244. * Override Camera._updateRigCameras
  47245. */
  47246. TargetCamera.prototype._updateRigCameras = function () {
  47247. var camLeft = this._rigCameras[0];
  47248. var camRight = this._rigCameras[1];
  47249. switch (this.cameraRigMode) {
  47250. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47251. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47252. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47253. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47254. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47255. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47256. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47257. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47258. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47259. camLeft.setTarget(this.getTarget());
  47260. camRight.setTarget(this.getTarget());
  47261. break;
  47262. case BABYLON.Camera.RIG_MODE_VR:
  47263. if (camLeft.rotationQuaternion) {
  47264. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47265. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47266. }
  47267. else {
  47268. camLeft.rotation.copyFrom(this.rotation);
  47269. camRight.rotation.copyFrom(this.rotation);
  47270. }
  47271. camLeft.position.copyFrom(this.position);
  47272. camRight.position.copyFrom(this.position);
  47273. break;
  47274. }
  47275. _super.prototype._updateRigCameras.call(this);
  47276. };
  47277. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47278. if (!this._rigCamTransformMatrix) {
  47279. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47280. }
  47281. var target = this.getTarget();
  47282. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47283. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47284. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47285. };
  47286. TargetCamera.prototype.getClassName = function () {
  47287. return "TargetCamera";
  47288. };
  47289. __decorate([
  47290. BABYLON.serializeAsVector3()
  47291. ], TargetCamera.prototype, "rotation", void 0);
  47292. __decorate([
  47293. BABYLON.serialize()
  47294. ], TargetCamera.prototype, "speed", void 0);
  47295. __decorate([
  47296. BABYLON.serializeAsMeshReference("lockedTargetId")
  47297. ], TargetCamera.prototype, "lockedTarget", void 0);
  47298. return TargetCamera;
  47299. }(BABYLON.Camera));
  47300. BABYLON.TargetCamera = TargetCamera;
  47301. })(BABYLON || (BABYLON = {}));
  47302. //# sourceMappingURL=babylon.targetCamera.js.map
  47303. var BABYLON;
  47304. (function (BABYLON) {
  47305. var FreeCameraMouseInput = /** @class */ (function () {
  47306. function FreeCameraMouseInput(touchEnabled) {
  47307. if (touchEnabled === void 0) { touchEnabled = true; }
  47308. this.touchEnabled = touchEnabled;
  47309. this.buttons = [0, 1, 2];
  47310. this.angularSensibility = 2000.0;
  47311. this.previousPosition = null;
  47312. }
  47313. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47314. var _this = this;
  47315. var engine = this.camera.getEngine();
  47316. if (!this._pointerInput) {
  47317. this._pointerInput = function (p, s) {
  47318. var evt = p.event;
  47319. if (engine.isInVRExclusivePointerMode) {
  47320. return;
  47321. }
  47322. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47323. return;
  47324. }
  47325. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47326. return;
  47327. }
  47328. var srcElement = (evt.srcElement || evt.target);
  47329. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47330. try {
  47331. srcElement.setPointerCapture(evt.pointerId);
  47332. }
  47333. catch (e) {
  47334. //Nothing to do with the error. Execution will continue.
  47335. }
  47336. _this.previousPosition = {
  47337. x: evt.clientX,
  47338. y: evt.clientY
  47339. };
  47340. if (!noPreventDefault) {
  47341. evt.preventDefault();
  47342. element.focus();
  47343. }
  47344. }
  47345. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47346. try {
  47347. srcElement.releasePointerCapture(evt.pointerId);
  47348. }
  47349. catch (e) {
  47350. //Nothing to do with the error.
  47351. }
  47352. _this.previousPosition = null;
  47353. if (!noPreventDefault) {
  47354. evt.preventDefault();
  47355. }
  47356. }
  47357. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47358. if (!_this.previousPosition || engine.isPointerLock) {
  47359. return;
  47360. }
  47361. var offsetX = evt.clientX - _this.previousPosition.x;
  47362. if (_this.camera.getScene().useRightHandedSystem)
  47363. offsetX *= -1;
  47364. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47365. offsetX *= -1;
  47366. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47367. var offsetY = evt.clientY - _this.previousPosition.y;
  47368. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47369. _this.previousPosition = {
  47370. x: evt.clientX,
  47371. y: evt.clientY
  47372. };
  47373. if (!noPreventDefault) {
  47374. evt.preventDefault();
  47375. }
  47376. }
  47377. };
  47378. }
  47379. this._onMouseMove = function (evt) {
  47380. if (!engine.isPointerLock) {
  47381. return;
  47382. }
  47383. if (engine.isInVRExclusivePointerMode) {
  47384. return;
  47385. }
  47386. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47387. if (_this.camera.getScene().useRightHandedSystem)
  47388. offsetX *= -1;
  47389. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47390. offsetX *= -1;
  47391. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47392. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47393. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47394. _this.previousPosition = null;
  47395. if (!noPreventDefault) {
  47396. evt.preventDefault();
  47397. }
  47398. };
  47399. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47400. element.addEventListener("mousemove", this._onMouseMove, false);
  47401. };
  47402. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47403. if (this._observer && element) {
  47404. this.camera.getScene().onPointerObservable.remove(this._observer);
  47405. if (this._onMouseMove) {
  47406. element.removeEventListener("mousemove", this._onMouseMove);
  47407. }
  47408. this._observer = null;
  47409. this._onMouseMove = null;
  47410. this.previousPosition = null;
  47411. }
  47412. };
  47413. FreeCameraMouseInput.prototype.getClassName = function () {
  47414. return "FreeCameraMouseInput";
  47415. };
  47416. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47417. return "mouse";
  47418. };
  47419. __decorate([
  47420. BABYLON.serialize()
  47421. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47422. __decorate([
  47423. BABYLON.serialize()
  47424. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47425. return FreeCameraMouseInput;
  47426. }());
  47427. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47428. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47429. })(BABYLON || (BABYLON = {}));
  47430. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47431. var BABYLON;
  47432. (function (BABYLON) {
  47433. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47434. function FreeCameraKeyboardMoveInput() {
  47435. this._keys = new Array();
  47436. this.keysUp = [38];
  47437. this.keysDown = [40];
  47438. this.keysLeft = [37];
  47439. this.keysRight = [39];
  47440. }
  47441. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47442. var _this = this;
  47443. if (this._onCanvasBlurObserver) {
  47444. return;
  47445. }
  47446. this._scene = this.camera.getScene();
  47447. this._engine = this._scene.getEngine();
  47448. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47449. _this._keys = [];
  47450. });
  47451. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47452. var evt = info.event;
  47453. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47454. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47455. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47456. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47457. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47458. var index = _this._keys.indexOf(evt.keyCode);
  47459. if (index === -1) {
  47460. _this._keys.push(evt.keyCode);
  47461. }
  47462. if (!noPreventDefault) {
  47463. evt.preventDefault();
  47464. }
  47465. }
  47466. }
  47467. else {
  47468. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47469. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47470. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47471. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47472. var index = _this._keys.indexOf(evt.keyCode);
  47473. if (index >= 0) {
  47474. _this._keys.splice(index, 1);
  47475. }
  47476. if (!noPreventDefault) {
  47477. evt.preventDefault();
  47478. }
  47479. }
  47480. }
  47481. });
  47482. };
  47483. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47484. if (this._scene) {
  47485. if (this._onKeyboardObserver) {
  47486. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47487. }
  47488. if (this._onCanvasBlurObserver) {
  47489. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47490. }
  47491. this._onKeyboardObserver = null;
  47492. this._onCanvasBlurObserver = null;
  47493. }
  47494. this._keys = [];
  47495. };
  47496. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47497. if (this._onKeyboardObserver) {
  47498. var camera = this.camera;
  47499. // Keyboard
  47500. for (var index = 0; index < this._keys.length; index++) {
  47501. var keyCode = this._keys[index];
  47502. var speed = camera._computeLocalCameraSpeed();
  47503. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47504. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47505. }
  47506. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47507. camera._localDirection.copyFromFloats(0, 0, speed);
  47508. }
  47509. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47510. camera._localDirection.copyFromFloats(speed, 0, 0);
  47511. }
  47512. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47513. camera._localDirection.copyFromFloats(0, 0, -speed);
  47514. }
  47515. if (camera.getScene().useRightHandedSystem) {
  47516. camera._localDirection.z *= -1;
  47517. }
  47518. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47519. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47520. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47521. }
  47522. }
  47523. };
  47524. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47525. return "FreeCameraKeyboardMoveInput";
  47526. };
  47527. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47528. this._keys = [];
  47529. };
  47530. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47531. return "keyboard";
  47532. };
  47533. __decorate([
  47534. BABYLON.serialize()
  47535. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47536. __decorate([
  47537. BABYLON.serialize()
  47538. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47539. __decorate([
  47540. BABYLON.serialize()
  47541. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47542. __decorate([
  47543. BABYLON.serialize()
  47544. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47545. return FreeCameraKeyboardMoveInput;
  47546. }());
  47547. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47548. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47549. })(BABYLON || (BABYLON = {}));
  47550. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47551. var BABYLON;
  47552. (function (BABYLON) {
  47553. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47554. __extends(FreeCameraInputsManager, _super);
  47555. function FreeCameraInputsManager(camera) {
  47556. return _super.call(this, camera) || this;
  47557. }
  47558. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47559. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47560. return this;
  47561. };
  47562. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47563. if (touchEnabled === void 0) { touchEnabled = true; }
  47564. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47565. return this;
  47566. };
  47567. FreeCameraInputsManager.prototype.addGamepad = function () {
  47568. this.add(new BABYLON.FreeCameraGamepadInput());
  47569. return this;
  47570. };
  47571. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47572. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47573. return this;
  47574. };
  47575. FreeCameraInputsManager.prototype.addTouch = function () {
  47576. this.add(new BABYLON.FreeCameraTouchInput());
  47577. return this;
  47578. };
  47579. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47580. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47581. return this;
  47582. };
  47583. return FreeCameraInputsManager;
  47584. }(BABYLON.CameraInputsManager));
  47585. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47586. })(BABYLON || (BABYLON = {}));
  47587. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47588. var BABYLON;
  47589. (function (BABYLON) {
  47590. var FreeCamera = /** @class */ (function (_super) {
  47591. __extends(FreeCamera, _super);
  47592. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47593. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47594. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47595. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47596. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47597. _this.checkCollisions = false;
  47598. _this.applyGravity = false;
  47599. _this._needMoveForGravity = false;
  47600. _this._oldPosition = BABYLON.Vector3.Zero();
  47601. _this._diffPosition = BABYLON.Vector3.Zero();
  47602. _this._newPosition = BABYLON.Vector3.Zero();
  47603. // Collisions
  47604. _this._collisionMask = -1;
  47605. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47606. if (collidedMesh === void 0) { collidedMesh = null; }
  47607. //TODO move this to the collision coordinator!
  47608. if (_this.getScene().workerCollisions)
  47609. newPosition.multiplyInPlace(_this._collider._radius);
  47610. var updatePosition = function (newPos) {
  47611. _this._newPosition.copyFrom(newPos);
  47612. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47613. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47614. _this.position.addInPlace(_this._diffPosition);
  47615. if (_this.onCollide && collidedMesh) {
  47616. _this.onCollide(collidedMesh);
  47617. }
  47618. }
  47619. };
  47620. updatePosition(newPosition);
  47621. };
  47622. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47623. _this.inputs.addKeyboard().addMouse();
  47624. return _this;
  47625. }
  47626. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47627. //-- begin properties for backward compatibility for inputs
  47628. /**
  47629. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47630. * Higher values reduce sensitivity.
  47631. */
  47632. get: function () {
  47633. var mouse = this.inputs.attached["mouse"];
  47634. if (mouse)
  47635. return mouse.angularSensibility;
  47636. return 0;
  47637. },
  47638. /**
  47639. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47640. * Higher values reduce sensitivity.
  47641. */
  47642. set: function (value) {
  47643. var mouse = this.inputs.attached["mouse"];
  47644. if (mouse)
  47645. mouse.angularSensibility = value;
  47646. },
  47647. enumerable: true,
  47648. configurable: true
  47649. });
  47650. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47651. get: function () {
  47652. var keyboard = this.inputs.attached["keyboard"];
  47653. if (keyboard)
  47654. return keyboard.keysUp;
  47655. return [];
  47656. },
  47657. set: function (value) {
  47658. var keyboard = this.inputs.attached["keyboard"];
  47659. if (keyboard)
  47660. keyboard.keysUp = value;
  47661. },
  47662. enumerable: true,
  47663. configurable: true
  47664. });
  47665. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47666. get: function () {
  47667. var keyboard = this.inputs.attached["keyboard"];
  47668. if (keyboard)
  47669. return keyboard.keysDown;
  47670. return [];
  47671. },
  47672. set: function (value) {
  47673. var keyboard = this.inputs.attached["keyboard"];
  47674. if (keyboard)
  47675. keyboard.keysDown = value;
  47676. },
  47677. enumerable: true,
  47678. configurable: true
  47679. });
  47680. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47681. get: function () {
  47682. var keyboard = this.inputs.attached["keyboard"];
  47683. if (keyboard)
  47684. return keyboard.keysLeft;
  47685. return [];
  47686. },
  47687. set: function (value) {
  47688. var keyboard = this.inputs.attached["keyboard"];
  47689. if (keyboard)
  47690. keyboard.keysLeft = value;
  47691. },
  47692. enumerable: true,
  47693. configurable: true
  47694. });
  47695. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47696. get: function () {
  47697. var keyboard = this.inputs.attached["keyboard"];
  47698. if (keyboard)
  47699. return keyboard.keysRight;
  47700. return [];
  47701. },
  47702. set: function (value) {
  47703. var keyboard = this.inputs.attached["keyboard"];
  47704. if (keyboard)
  47705. keyboard.keysRight = value;
  47706. },
  47707. enumerable: true,
  47708. configurable: true
  47709. });
  47710. // Controls
  47711. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47712. this.inputs.attachElement(element, noPreventDefault);
  47713. };
  47714. FreeCamera.prototype.detachControl = function (element) {
  47715. this.inputs.detachElement(element);
  47716. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47717. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47718. };
  47719. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47720. get: function () {
  47721. return this._collisionMask;
  47722. },
  47723. set: function (mask) {
  47724. this._collisionMask = !isNaN(mask) ? mask : -1;
  47725. },
  47726. enumerable: true,
  47727. configurable: true
  47728. });
  47729. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47730. var globalPosition;
  47731. if (this.parent) {
  47732. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47733. }
  47734. else {
  47735. globalPosition = this.position;
  47736. }
  47737. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47738. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47739. if (!this._collider) {
  47740. this._collider = new BABYLON.Collider();
  47741. }
  47742. this._collider._radius = this.ellipsoid;
  47743. this._collider.collisionMask = this._collisionMask;
  47744. //no need for clone, as long as gravity is not on.
  47745. var actualDisplacement = displacement;
  47746. //add gravity to the direction to prevent the dual-collision checking
  47747. if (this.applyGravity) {
  47748. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47749. actualDisplacement = displacement.add(this.getScene().gravity);
  47750. }
  47751. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47752. };
  47753. FreeCamera.prototype._checkInputs = function () {
  47754. if (!this._localDirection) {
  47755. this._localDirection = BABYLON.Vector3.Zero();
  47756. this._transformedDirection = BABYLON.Vector3.Zero();
  47757. }
  47758. this.inputs.checkInputs();
  47759. _super.prototype._checkInputs.call(this);
  47760. };
  47761. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47762. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47763. };
  47764. FreeCamera.prototype._updatePosition = function () {
  47765. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47766. this._collideWithWorld(this.cameraDirection);
  47767. }
  47768. else {
  47769. _super.prototype._updatePosition.call(this);
  47770. }
  47771. };
  47772. FreeCamera.prototype.dispose = function () {
  47773. this.inputs.clear();
  47774. _super.prototype.dispose.call(this);
  47775. };
  47776. FreeCamera.prototype.getClassName = function () {
  47777. return "FreeCamera";
  47778. };
  47779. __decorate([
  47780. BABYLON.serializeAsVector3()
  47781. ], FreeCamera.prototype, "ellipsoid", void 0);
  47782. __decorate([
  47783. BABYLON.serializeAsVector3()
  47784. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47785. __decorate([
  47786. BABYLON.serialize()
  47787. ], FreeCamera.prototype, "checkCollisions", void 0);
  47788. __decorate([
  47789. BABYLON.serialize()
  47790. ], FreeCamera.prototype, "applyGravity", void 0);
  47791. return FreeCamera;
  47792. }(BABYLON.TargetCamera));
  47793. BABYLON.FreeCamera = FreeCamera;
  47794. })(BABYLON || (BABYLON = {}));
  47795. //# sourceMappingURL=babylon.freeCamera.js.map
  47796. var BABYLON;
  47797. (function (BABYLON) {
  47798. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47799. function ArcRotateCameraKeyboardMoveInput() {
  47800. this._keys = new Array();
  47801. this.keysUp = [38];
  47802. this.keysDown = [40];
  47803. this.keysLeft = [37];
  47804. this.keysRight = [39];
  47805. this.keysReset = [220];
  47806. this.panningSensibility = 50.0;
  47807. this.zoomingSensibility = 25.0;
  47808. this.useAltToZoom = true;
  47809. }
  47810. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47811. var _this = this;
  47812. if (this._onCanvasBlurObserver) {
  47813. return;
  47814. }
  47815. this._scene = this.camera.getScene();
  47816. this._engine = this._scene.getEngine();
  47817. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47818. _this._keys = [];
  47819. });
  47820. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47821. var evt = info.event;
  47822. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47823. _this._ctrlPressed = evt.ctrlKey;
  47824. _this._altPressed = evt.altKey;
  47825. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47826. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47827. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47828. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47829. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47830. var index = _this._keys.indexOf(evt.keyCode);
  47831. if (index === -1) {
  47832. _this._keys.push(evt.keyCode);
  47833. }
  47834. if (evt.preventDefault) {
  47835. if (!noPreventDefault) {
  47836. evt.preventDefault();
  47837. }
  47838. }
  47839. }
  47840. }
  47841. else {
  47842. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47843. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47844. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47845. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47846. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47847. var index = _this._keys.indexOf(evt.keyCode);
  47848. if (index >= 0) {
  47849. _this._keys.splice(index, 1);
  47850. }
  47851. if (evt.preventDefault) {
  47852. if (!noPreventDefault) {
  47853. evt.preventDefault();
  47854. }
  47855. }
  47856. }
  47857. }
  47858. });
  47859. };
  47860. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47861. if (this._scene) {
  47862. if (this._onKeyboardObserver) {
  47863. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47864. }
  47865. if (this._onCanvasBlurObserver) {
  47866. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47867. }
  47868. this._onKeyboardObserver = null;
  47869. this._onCanvasBlurObserver = null;
  47870. }
  47871. this._keys = [];
  47872. };
  47873. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47874. if (this._onKeyboardObserver) {
  47875. var camera = this.camera;
  47876. for (var index = 0; index < this._keys.length; index++) {
  47877. var keyCode = this._keys[index];
  47878. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47879. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47880. camera.inertialPanningX -= 1 / this.panningSensibility;
  47881. }
  47882. else {
  47883. camera.inertialAlphaOffset -= 0.01;
  47884. }
  47885. }
  47886. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47887. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47888. camera.inertialPanningY += 1 / this.panningSensibility;
  47889. }
  47890. else if (this._altPressed && this.useAltToZoom) {
  47891. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47892. }
  47893. else {
  47894. camera.inertialBetaOffset -= 0.01;
  47895. }
  47896. }
  47897. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47898. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47899. camera.inertialPanningX += 1 / this.panningSensibility;
  47900. }
  47901. else {
  47902. camera.inertialAlphaOffset += 0.01;
  47903. }
  47904. }
  47905. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47906. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47907. camera.inertialPanningY -= 1 / this.panningSensibility;
  47908. }
  47909. else if (this._altPressed && this.useAltToZoom) {
  47910. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47911. }
  47912. else {
  47913. camera.inertialBetaOffset += 0.01;
  47914. }
  47915. }
  47916. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47917. camera.restoreState();
  47918. }
  47919. }
  47920. }
  47921. };
  47922. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47923. return "ArcRotateCameraKeyboardMoveInput";
  47924. };
  47925. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47926. return "keyboard";
  47927. };
  47928. __decorate([
  47929. BABYLON.serialize()
  47930. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47931. __decorate([
  47932. BABYLON.serialize()
  47933. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47934. __decorate([
  47935. BABYLON.serialize()
  47936. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47937. __decorate([
  47938. BABYLON.serialize()
  47939. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47940. __decorate([
  47941. BABYLON.serialize()
  47942. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47943. __decorate([
  47944. BABYLON.serialize()
  47945. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47946. __decorate([
  47947. BABYLON.serialize()
  47948. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47949. __decorate([
  47950. BABYLON.serialize()
  47951. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47952. return ArcRotateCameraKeyboardMoveInput;
  47953. }());
  47954. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47955. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47956. })(BABYLON || (BABYLON = {}));
  47957. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47958. var BABYLON;
  47959. (function (BABYLON) {
  47960. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47961. function ArcRotateCameraMouseWheelInput() {
  47962. this.wheelPrecision = 3.0;
  47963. /**
  47964. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47965. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47966. */
  47967. this.wheelDeltaPercentage = 0;
  47968. }
  47969. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47970. var _this = this;
  47971. this._wheel = function (p, s) {
  47972. //sanity check - this should be a PointerWheel event.
  47973. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47974. return;
  47975. var event = p.event;
  47976. var delta = 0;
  47977. if (event.wheelDelta) {
  47978. if (_this.wheelDeltaPercentage) {
  47979. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47980. if (event.wheelDelta > 0) {
  47981. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47982. }
  47983. else {
  47984. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47985. }
  47986. }
  47987. else {
  47988. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47989. }
  47990. }
  47991. else if (event.detail) {
  47992. delta = -event.detail / _this.wheelPrecision;
  47993. }
  47994. if (delta)
  47995. _this.camera.inertialRadiusOffset += delta;
  47996. if (event.preventDefault) {
  47997. if (!noPreventDefault) {
  47998. event.preventDefault();
  47999. }
  48000. }
  48001. };
  48002. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48003. };
  48004. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48005. if (this._observer && element) {
  48006. this.camera.getScene().onPointerObservable.remove(this._observer);
  48007. this._observer = null;
  48008. this._wheel = null;
  48009. }
  48010. };
  48011. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48012. return "ArcRotateCameraMouseWheelInput";
  48013. };
  48014. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48015. return "mousewheel";
  48016. };
  48017. __decorate([
  48018. BABYLON.serialize()
  48019. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48020. __decorate([
  48021. BABYLON.serialize()
  48022. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48023. return ArcRotateCameraMouseWheelInput;
  48024. }());
  48025. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48026. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48027. })(BABYLON || (BABYLON = {}));
  48028. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48029. var BABYLON;
  48030. (function (BABYLON) {
  48031. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48032. function ArcRotateCameraPointersInput() {
  48033. this.buttons = [0, 1, 2];
  48034. this.angularSensibilityX = 1000.0;
  48035. this.angularSensibilityY = 1000.0;
  48036. this.pinchPrecision = 12.0;
  48037. /**
  48038. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48039. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48040. */
  48041. this.pinchDeltaPercentage = 0;
  48042. this.panningSensibility = 1000.0;
  48043. this.multiTouchPanning = true;
  48044. this.multiTouchPanAndZoom = true;
  48045. this._isPanClick = false;
  48046. this.pinchInwards = true;
  48047. }
  48048. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48049. var _this = this;
  48050. var engine = this.camera.getEngine();
  48051. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48052. var pointA = null;
  48053. var pointB = null;
  48054. var previousPinchSquaredDistance = 0;
  48055. var initialDistance = 0;
  48056. var twoFingerActivityCount = 0;
  48057. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48058. this._pointerInput = function (p, s) {
  48059. var evt = p.event;
  48060. var isTouch = p.event.pointerType === "touch";
  48061. if (engine.isInVRExclusivePointerMode) {
  48062. return;
  48063. }
  48064. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48065. return;
  48066. }
  48067. var srcElement = (evt.srcElement || evt.target);
  48068. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48069. try {
  48070. srcElement.setPointerCapture(evt.pointerId);
  48071. }
  48072. catch (e) {
  48073. //Nothing to do with the error. Execution will continue.
  48074. }
  48075. // Manage panning with pan button click
  48076. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48077. // manage pointers
  48078. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48079. if (pointA === null) {
  48080. pointA = cacheSoloPointer;
  48081. }
  48082. else if (pointB === null) {
  48083. pointB = cacheSoloPointer;
  48084. }
  48085. if (!noPreventDefault) {
  48086. evt.preventDefault();
  48087. element.focus();
  48088. }
  48089. }
  48090. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48091. _this.camera.restoreState();
  48092. }
  48093. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48094. try {
  48095. srcElement.releasePointerCapture(evt.pointerId);
  48096. }
  48097. catch (e) {
  48098. //Nothing to do with the error.
  48099. }
  48100. cacheSoloPointer = null;
  48101. previousPinchSquaredDistance = 0;
  48102. previousMultiTouchPanPosition.isPaning = false;
  48103. previousMultiTouchPanPosition.isPinching = false;
  48104. twoFingerActivityCount = 0;
  48105. initialDistance = 0;
  48106. if (!isTouch) {
  48107. pointB = null; // Mouse and pen are mono pointer
  48108. }
  48109. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48110. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48111. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48112. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48113. if (engine._badOS) {
  48114. pointA = pointB = null;
  48115. }
  48116. else {
  48117. //only remove the impacted pointer in case of multitouch allowing on most
  48118. //platforms switching from rotate to zoom and pan seamlessly.
  48119. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48120. pointA = pointB;
  48121. pointB = null;
  48122. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48123. }
  48124. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48125. pointB = null;
  48126. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48127. }
  48128. else {
  48129. pointA = pointB = null;
  48130. }
  48131. }
  48132. if (!noPreventDefault) {
  48133. evt.preventDefault();
  48134. }
  48135. }
  48136. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48137. if (!noPreventDefault) {
  48138. evt.preventDefault();
  48139. }
  48140. // One button down
  48141. if (pointA && pointB === null && cacheSoloPointer) {
  48142. if (_this.panningSensibility !== 0 &&
  48143. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48144. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48145. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48146. }
  48147. else {
  48148. var offsetX = evt.clientX - cacheSoloPointer.x;
  48149. var offsetY = evt.clientY - cacheSoloPointer.y;
  48150. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48151. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48152. }
  48153. cacheSoloPointer.x = evt.clientX;
  48154. cacheSoloPointer.y = evt.clientY;
  48155. }
  48156. // Two buttons down: pinch/pan
  48157. else if (pointA && pointB) {
  48158. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48159. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48160. ed.x = evt.clientX;
  48161. ed.y = evt.clientY;
  48162. var direction = _this.pinchInwards ? 1 : -1;
  48163. var distX = pointA.x - pointB.x;
  48164. var distY = pointA.y - pointB.y;
  48165. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48166. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48167. if (previousPinchSquaredDistance === 0) {
  48168. initialDistance = pinchDistance;
  48169. previousPinchSquaredDistance = pinchSquaredDistance;
  48170. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48171. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48172. return;
  48173. }
  48174. if (_this.multiTouchPanAndZoom) {
  48175. if (_this.pinchDeltaPercentage) {
  48176. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48177. }
  48178. else {
  48179. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48180. (_this.pinchPrecision *
  48181. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48182. direction);
  48183. }
  48184. if (_this.panningSensibility !== 0) {
  48185. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48186. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48187. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48188. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48189. previousMultiTouchPanPosition.x = pointersCenterX;
  48190. previousMultiTouchPanPosition.y = pointersCenterY;
  48191. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48192. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48193. }
  48194. }
  48195. else {
  48196. twoFingerActivityCount++;
  48197. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48198. if (_this.pinchDeltaPercentage) {
  48199. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48200. }
  48201. else {
  48202. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48203. (_this.pinchPrecision *
  48204. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48205. direction);
  48206. }
  48207. previousMultiTouchPanPosition.isPaning = false;
  48208. previousMultiTouchPanPosition.isPinching = true;
  48209. }
  48210. else {
  48211. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48212. if (!previousMultiTouchPanPosition.isPaning) {
  48213. previousMultiTouchPanPosition.isPaning = true;
  48214. previousMultiTouchPanPosition.isPinching = false;
  48215. previousMultiTouchPanPosition.x = ed.x;
  48216. previousMultiTouchPanPosition.y = ed.y;
  48217. return;
  48218. }
  48219. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48220. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48221. }
  48222. }
  48223. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48224. previousMultiTouchPanPosition.x = ed.x;
  48225. previousMultiTouchPanPosition.y = ed.y;
  48226. }
  48227. }
  48228. previousPinchSquaredDistance = pinchSquaredDistance;
  48229. }
  48230. }
  48231. };
  48232. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48233. this._onContextMenu = function (evt) {
  48234. evt.preventDefault();
  48235. };
  48236. if (!this.camera._useCtrlForPanning) {
  48237. element.addEventListener("contextmenu", this._onContextMenu, false);
  48238. }
  48239. this._onLostFocus = function () {
  48240. //this._keys = [];
  48241. pointA = pointB = null;
  48242. previousPinchSquaredDistance = 0;
  48243. previousMultiTouchPanPosition.isPaning = false;
  48244. previousMultiTouchPanPosition.isPinching = false;
  48245. twoFingerActivityCount = 0;
  48246. cacheSoloPointer = null;
  48247. initialDistance = 0;
  48248. };
  48249. this._onMouseMove = function (evt) {
  48250. if (!engine.isPointerLock) {
  48251. return;
  48252. }
  48253. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48254. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48255. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48256. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48257. if (!noPreventDefault) {
  48258. evt.preventDefault();
  48259. }
  48260. };
  48261. this._onGestureStart = function (e) {
  48262. if (window.MSGesture === undefined) {
  48263. return;
  48264. }
  48265. if (!_this._MSGestureHandler) {
  48266. _this._MSGestureHandler = new MSGesture();
  48267. _this._MSGestureHandler.target = element;
  48268. }
  48269. _this._MSGestureHandler.addPointer(e.pointerId);
  48270. };
  48271. this._onGesture = function (e) {
  48272. _this.camera.radius *= e.scale;
  48273. if (e.preventDefault) {
  48274. if (!noPreventDefault) {
  48275. e.stopPropagation();
  48276. e.preventDefault();
  48277. }
  48278. }
  48279. };
  48280. element.addEventListener("mousemove", this._onMouseMove, false);
  48281. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48282. element.addEventListener("MSGestureChange", this._onGesture, false);
  48283. BABYLON.Tools.RegisterTopRootEvents([
  48284. { name: "blur", handler: this._onLostFocus }
  48285. ]);
  48286. };
  48287. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48288. if (this._onLostFocus) {
  48289. BABYLON.Tools.UnregisterTopRootEvents([
  48290. { name: "blur", handler: this._onLostFocus }
  48291. ]);
  48292. }
  48293. if (element && this._observer) {
  48294. this.camera.getScene().onPointerObservable.remove(this._observer);
  48295. this._observer = null;
  48296. if (this._onContextMenu) {
  48297. element.removeEventListener("contextmenu", this._onContextMenu);
  48298. }
  48299. if (this._onMouseMove) {
  48300. element.removeEventListener("mousemove", this._onMouseMove);
  48301. }
  48302. if (this._onGestureStart) {
  48303. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48304. }
  48305. if (this._onGesture) {
  48306. element.removeEventListener("MSGestureChange", this._onGesture);
  48307. }
  48308. this._isPanClick = false;
  48309. this.pinchInwards = true;
  48310. this._onMouseMove = null;
  48311. this._onGestureStart = null;
  48312. this._onGesture = null;
  48313. this._MSGestureHandler = null;
  48314. this._onLostFocus = null;
  48315. this._onContextMenu = null;
  48316. }
  48317. };
  48318. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48319. return "ArcRotateCameraPointersInput";
  48320. };
  48321. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48322. return "pointers";
  48323. };
  48324. __decorate([
  48325. BABYLON.serialize()
  48326. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48327. __decorate([
  48328. BABYLON.serialize()
  48329. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48330. __decorate([
  48331. BABYLON.serialize()
  48332. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48333. __decorate([
  48334. BABYLON.serialize()
  48335. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48336. __decorate([
  48337. BABYLON.serialize()
  48338. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48339. __decorate([
  48340. BABYLON.serialize()
  48341. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48342. __decorate([
  48343. BABYLON.serialize()
  48344. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48345. __decorate([
  48346. BABYLON.serialize()
  48347. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48348. return ArcRotateCameraPointersInput;
  48349. }());
  48350. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48351. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48352. })(BABYLON || (BABYLON = {}));
  48353. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48354. var BABYLON;
  48355. (function (BABYLON) {
  48356. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48357. __extends(ArcRotateCameraInputsManager, _super);
  48358. function ArcRotateCameraInputsManager(camera) {
  48359. return _super.call(this, camera) || this;
  48360. }
  48361. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48362. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48363. return this;
  48364. };
  48365. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48366. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48367. return this;
  48368. };
  48369. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48370. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48371. return this;
  48372. };
  48373. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48374. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48375. return this;
  48376. };
  48377. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48378. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48379. return this;
  48380. };
  48381. return ArcRotateCameraInputsManager;
  48382. }(BABYLON.CameraInputsManager));
  48383. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48384. })(BABYLON || (BABYLON = {}));
  48385. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48386. var BABYLON;
  48387. (function (BABYLON) {
  48388. var ArcRotateCamera = /** @class */ (function (_super) {
  48389. __extends(ArcRotateCamera, _super);
  48390. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48391. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48392. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48393. _this.inertialAlphaOffset = 0;
  48394. _this.inertialBetaOffset = 0;
  48395. _this.inertialRadiusOffset = 0;
  48396. _this.lowerAlphaLimit = null;
  48397. _this.upperAlphaLimit = null;
  48398. _this.lowerBetaLimit = 0.01;
  48399. _this.upperBetaLimit = Math.PI;
  48400. _this.lowerRadiusLimit = null;
  48401. _this.upperRadiusLimit = null;
  48402. _this.inertialPanningX = 0;
  48403. _this.inertialPanningY = 0;
  48404. _this.pinchToPanMaxDistance = 20;
  48405. _this.panningDistanceLimit = null;
  48406. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48407. _this.panningInertia = 0.9;
  48408. //-- end properties for backward compatibility for inputs
  48409. _this.zoomOnFactor = 1;
  48410. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48411. _this.allowUpsideDown = true;
  48412. _this._viewMatrix = new BABYLON.Matrix();
  48413. // Panning
  48414. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48415. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48416. _this.checkCollisions = false;
  48417. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48418. _this._previousPosition = BABYLON.Vector3.Zero();
  48419. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48420. _this._newPosition = BABYLON.Vector3.Zero();
  48421. _this._computationVector = BABYLON.Vector3.Zero();
  48422. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48423. if (collidedMesh === void 0) { collidedMesh = null; }
  48424. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48425. newPosition.multiplyInPlace(_this._collider._radius);
  48426. }
  48427. if (!collidedMesh) {
  48428. _this._previousPosition.copyFrom(_this.position);
  48429. }
  48430. else {
  48431. _this.setPosition(newPosition);
  48432. if (_this.onCollide) {
  48433. _this.onCollide(collidedMesh);
  48434. }
  48435. }
  48436. // Recompute because of constraints
  48437. var cosa = Math.cos(_this.alpha);
  48438. var sina = Math.sin(_this.alpha);
  48439. var cosb = Math.cos(_this.beta);
  48440. var sinb = Math.sin(_this.beta);
  48441. if (sinb === 0) {
  48442. sinb = 0.0001;
  48443. }
  48444. var target = _this._getTargetPosition();
  48445. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48446. target.addToRef(_this._computationVector, _this._newPosition);
  48447. _this.position.copyFrom(_this._newPosition);
  48448. var up = _this.upVector;
  48449. if (_this.allowUpsideDown && _this.beta < 0) {
  48450. up = up.clone();
  48451. up = up.negate();
  48452. }
  48453. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48454. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48455. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48456. _this._collisionTriggered = false;
  48457. };
  48458. _this._target = BABYLON.Vector3.Zero();
  48459. if (target) {
  48460. _this.setTarget(target);
  48461. }
  48462. _this.alpha = alpha;
  48463. _this.beta = beta;
  48464. _this.radius = radius;
  48465. _this.getViewMatrix();
  48466. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48467. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48468. return _this;
  48469. }
  48470. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48471. get: function () {
  48472. return this._target;
  48473. },
  48474. set: function (value) {
  48475. this.setTarget(value);
  48476. },
  48477. enumerable: true,
  48478. configurable: true
  48479. });
  48480. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48481. //-- begin properties for backward compatibility for inputs
  48482. get: function () {
  48483. var pointers = this.inputs.attached["pointers"];
  48484. if (pointers)
  48485. return pointers.angularSensibilityX;
  48486. return 0;
  48487. },
  48488. set: function (value) {
  48489. var pointers = this.inputs.attached["pointers"];
  48490. if (pointers) {
  48491. pointers.angularSensibilityX = value;
  48492. }
  48493. },
  48494. enumerable: true,
  48495. configurable: true
  48496. });
  48497. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48498. get: function () {
  48499. var pointers = this.inputs.attached["pointers"];
  48500. if (pointers)
  48501. return pointers.angularSensibilityY;
  48502. return 0;
  48503. },
  48504. set: function (value) {
  48505. var pointers = this.inputs.attached["pointers"];
  48506. if (pointers) {
  48507. pointers.angularSensibilityY = value;
  48508. }
  48509. },
  48510. enumerable: true,
  48511. configurable: true
  48512. });
  48513. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48514. get: function () {
  48515. var pointers = this.inputs.attached["pointers"];
  48516. if (pointers)
  48517. return pointers.pinchPrecision;
  48518. return 0;
  48519. },
  48520. set: function (value) {
  48521. var pointers = this.inputs.attached["pointers"];
  48522. if (pointers) {
  48523. pointers.pinchPrecision = value;
  48524. }
  48525. },
  48526. enumerable: true,
  48527. configurable: true
  48528. });
  48529. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48530. get: function () {
  48531. var pointers = this.inputs.attached["pointers"];
  48532. if (pointers)
  48533. return pointers.pinchDeltaPercentage;
  48534. return 0;
  48535. },
  48536. set: function (value) {
  48537. var pointers = this.inputs.attached["pointers"];
  48538. if (pointers) {
  48539. pointers.pinchDeltaPercentage = value;
  48540. }
  48541. },
  48542. enumerable: true,
  48543. configurable: true
  48544. });
  48545. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48546. get: function () {
  48547. var pointers = this.inputs.attached["pointers"];
  48548. if (pointers)
  48549. return pointers.panningSensibility;
  48550. return 0;
  48551. },
  48552. set: function (value) {
  48553. var pointers = this.inputs.attached["pointers"];
  48554. if (pointers) {
  48555. pointers.panningSensibility = value;
  48556. }
  48557. },
  48558. enumerable: true,
  48559. configurable: true
  48560. });
  48561. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48562. get: function () {
  48563. var keyboard = this.inputs.attached["keyboard"];
  48564. if (keyboard)
  48565. return keyboard.keysUp;
  48566. return [];
  48567. },
  48568. set: function (value) {
  48569. var keyboard = this.inputs.attached["keyboard"];
  48570. if (keyboard)
  48571. keyboard.keysUp = value;
  48572. },
  48573. enumerable: true,
  48574. configurable: true
  48575. });
  48576. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48577. get: function () {
  48578. var keyboard = this.inputs.attached["keyboard"];
  48579. if (keyboard)
  48580. return keyboard.keysDown;
  48581. return [];
  48582. },
  48583. set: function (value) {
  48584. var keyboard = this.inputs.attached["keyboard"];
  48585. if (keyboard)
  48586. keyboard.keysDown = value;
  48587. },
  48588. enumerable: true,
  48589. configurable: true
  48590. });
  48591. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48592. get: function () {
  48593. var keyboard = this.inputs.attached["keyboard"];
  48594. if (keyboard)
  48595. return keyboard.keysLeft;
  48596. return [];
  48597. },
  48598. set: function (value) {
  48599. var keyboard = this.inputs.attached["keyboard"];
  48600. if (keyboard)
  48601. keyboard.keysLeft = value;
  48602. },
  48603. enumerable: true,
  48604. configurable: true
  48605. });
  48606. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48607. get: function () {
  48608. var keyboard = this.inputs.attached["keyboard"];
  48609. if (keyboard)
  48610. return keyboard.keysRight;
  48611. return [];
  48612. },
  48613. set: function (value) {
  48614. var keyboard = this.inputs.attached["keyboard"];
  48615. if (keyboard)
  48616. keyboard.keysRight = value;
  48617. },
  48618. enumerable: true,
  48619. configurable: true
  48620. });
  48621. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48622. get: function () {
  48623. var mousewheel = this.inputs.attached["mousewheel"];
  48624. if (mousewheel)
  48625. return mousewheel.wheelPrecision;
  48626. return 0;
  48627. },
  48628. set: function (value) {
  48629. var mousewheel = this.inputs.attached["mousewheel"];
  48630. if (mousewheel)
  48631. mousewheel.wheelPrecision = value;
  48632. },
  48633. enumerable: true,
  48634. configurable: true
  48635. });
  48636. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48637. get: function () {
  48638. var mousewheel = this.inputs.attached["mousewheel"];
  48639. if (mousewheel)
  48640. return mousewheel.wheelDeltaPercentage;
  48641. return 0;
  48642. },
  48643. set: function (value) {
  48644. var mousewheel = this.inputs.attached["mousewheel"];
  48645. if (mousewheel)
  48646. mousewheel.wheelDeltaPercentage = value;
  48647. },
  48648. enumerable: true,
  48649. configurable: true
  48650. });
  48651. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48652. get: function () {
  48653. return this._bouncingBehavior;
  48654. },
  48655. enumerable: true,
  48656. configurable: true
  48657. });
  48658. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48659. get: function () {
  48660. return this._bouncingBehavior != null;
  48661. },
  48662. set: function (value) {
  48663. if (value === this.useBouncingBehavior) {
  48664. return;
  48665. }
  48666. if (value) {
  48667. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48668. this.addBehavior(this._bouncingBehavior);
  48669. }
  48670. else if (this._bouncingBehavior) {
  48671. this.removeBehavior(this._bouncingBehavior);
  48672. this._bouncingBehavior = null;
  48673. }
  48674. },
  48675. enumerable: true,
  48676. configurable: true
  48677. });
  48678. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48679. get: function () {
  48680. return this._framingBehavior;
  48681. },
  48682. enumerable: true,
  48683. configurable: true
  48684. });
  48685. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48686. get: function () {
  48687. return this._framingBehavior != null;
  48688. },
  48689. set: function (value) {
  48690. if (value === this.useFramingBehavior) {
  48691. return;
  48692. }
  48693. if (value) {
  48694. this._framingBehavior = new BABYLON.FramingBehavior();
  48695. this.addBehavior(this._framingBehavior);
  48696. }
  48697. else if (this._framingBehavior) {
  48698. this.removeBehavior(this._framingBehavior);
  48699. this._framingBehavior = null;
  48700. }
  48701. },
  48702. enumerable: true,
  48703. configurable: true
  48704. });
  48705. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48706. get: function () {
  48707. return this._autoRotationBehavior;
  48708. },
  48709. enumerable: true,
  48710. configurable: true
  48711. });
  48712. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48713. get: function () {
  48714. return this._autoRotationBehavior != null;
  48715. },
  48716. set: function (value) {
  48717. if (value === this.useAutoRotationBehavior) {
  48718. return;
  48719. }
  48720. if (value) {
  48721. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48722. this.addBehavior(this._autoRotationBehavior);
  48723. }
  48724. else if (this._autoRotationBehavior) {
  48725. this.removeBehavior(this._autoRotationBehavior);
  48726. this._autoRotationBehavior = null;
  48727. }
  48728. },
  48729. enumerable: true,
  48730. configurable: true
  48731. });
  48732. // Cache
  48733. ArcRotateCamera.prototype._initCache = function () {
  48734. _super.prototype._initCache.call(this);
  48735. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48736. this._cache.alpha = undefined;
  48737. this._cache.beta = undefined;
  48738. this._cache.radius = undefined;
  48739. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48740. };
  48741. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48742. if (!ignoreParentClass) {
  48743. _super.prototype._updateCache.call(this);
  48744. }
  48745. this._cache._target.copyFrom(this._getTargetPosition());
  48746. this._cache.alpha = this.alpha;
  48747. this._cache.beta = this.beta;
  48748. this._cache.radius = this.radius;
  48749. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48750. };
  48751. ArcRotateCamera.prototype._getTargetPosition = function () {
  48752. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48753. var pos = this._targetHost.getAbsolutePosition();
  48754. if (this._targetBoundingCenter) {
  48755. pos.addToRef(this._targetBoundingCenter, this._target);
  48756. }
  48757. else {
  48758. this._target.copyFrom(pos);
  48759. }
  48760. }
  48761. var lockedTargetPosition = this._getLockedTargetPosition();
  48762. if (lockedTargetPosition) {
  48763. return lockedTargetPosition;
  48764. }
  48765. return this._target;
  48766. };
  48767. ArcRotateCamera.prototype.storeState = function () {
  48768. this._storedAlpha = this.alpha;
  48769. this._storedBeta = this.beta;
  48770. this._storedRadius = this.radius;
  48771. this._storedTarget = this._getTargetPosition().clone();
  48772. return _super.prototype.storeState.call(this);
  48773. };
  48774. /**
  48775. * Restored camera state. You must call storeState() first
  48776. */
  48777. ArcRotateCamera.prototype._restoreStateValues = function () {
  48778. if (!_super.prototype._restoreStateValues.call(this)) {
  48779. return false;
  48780. }
  48781. this.alpha = this._storedAlpha;
  48782. this.beta = this._storedBeta;
  48783. this.radius = this._storedRadius;
  48784. this.setTarget(this._storedTarget.clone());
  48785. this.inertialAlphaOffset = 0;
  48786. this.inertialBetaOffset = 0;
  48787. this.inertialRadiusOffset = 0;
  48788. this.inertialPanningX = 0;
  48789. this.inertialPanningY = 0;
  48790. return true;
  48791. };
  48792. // Synchronized
  48793. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48794. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48795. return false;
  48796. return this._cache._target.equals(this._getTargetPosition())
  48797. && this._cache.alpha === this.alpha
  48798. && this._cache.beta === this.beta
  48799. && this._cache.radius === this.radius
  48800. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48801. };
  48802. // Methods
  48803. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48804. var _this = this;
  48805. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48806. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48807. this._useCtrlForPanning = useCtrlForPanning;
  48808. this._panningMouseButton = panningMouseButton;
  48809. this.inputs.attachElement(element, noPreventDefault);
  48810. this._reset = function () {
  48811. _this.inertialAlphaOffset = 0;
  48812. _this.inertialBetaOffset = 0;
  48813. _this.inertialRadiusOffset = 0;
  48814. _this.inertialPanningX = 0;
  48815. _this.inertialPanningY = 0;
  48816. };
  48817. };
  48818. ArcRotateCamera.prototype.detachControl = function (element) {
  48819. this.inputs.detachElement(element);
  48820. if (this._reset) {
  48821. this._reset();
  48822. }
  48823. };
  48824. ArcRotateCamera.prototype._checkInputs = function () {
  48825. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48826. if (this._collisionTriggered) {
  48827. return;
  48828. }
  48829. this.inputs.checkInputs();
  48830. // Inertia
  48831. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48832. var inertialAlphaOffset = this.inertialAlphaOffset;
  48833. if (this.beta <= 0)
  48834. inertialAlphaOffset *= -1;
  48835. if (this.getScene().useRightHandedSystem)
  48836. inertialAlphaOffset *= -1;
  48837. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48838. inertialAlphaOffset *= -1;
  48839. this.alpha += inertialAlphaOffset;
  48840. this.beta += this.inertialBetaOffset;
  48841. this.radius -= this.inertialRadiusOffset;
  48842. this.inertialAlphaOffset *= this.inertia;
  48843. this.inertialBetaOffset *= this.inertia;
  48844. this.inertialRadiusOffset *= this.inertia;
  48845. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48846. this.inertialAlphaOffset = 0;
  48847. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48848. this.inertialBetaOffset = 0;
  48849. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48850. this.inertialRadiusOffset = 0;
  48851. }
  48852. // Panning inertia
  48853. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48854. if (!this._localDirection) {
  48855. this._localDirection = BABYLON.Vector3.Zero();
  48856. this._transformedDirection = BABYLON.Vector3.Zero();
  48857. }
  48858. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48859. this._localDirection.multiplyInPlace(this.panningAxis);
  48860. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48861. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48862. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48863. if (!this.panningAxis.y) {
  48864. this._transformedDirection.y = 0;
  48865. }
  48866. if (!this._targetHost) {
  48867. if (this.panningDistanceLimit) {
  48868. this._transformedDirection.addInPlace(this._target);
  48869. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48870. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48871. this._target.copyFrom(this._transformedDirection);
  48872. }
  48873. }
  48874. else {
  48875. this._target.addInPlace(this._transformedDirection);
  48876. }
  48877. }
  48878. this.inertialPanningX *= this.panningInertia;
  48879. this.inertialPanningY *= this.panningInertia;
  48880. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48881. this.inertialPanningX = 0;
  48882. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48883. this.inertialPanningY = 0;
  48884. }
  48885. // Limits
  48886. this._checkLimits();
  48887. _super.prototype._checkInputs.call(this);
  48888. };
  48889. ArcRotateCamera.prototype._checkLimits = function () {
  48890. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48891. if (this.allowUpsideDown && this.beta > Math.PI) {
  48892. this.beta = this.beta - (2 * Math.PI);
  48893. }
  48894. }
  48895. else {
  48896. if (this.beta < this.lowerBetaLimit) {
  48897. this.beta = this.lowerBetaLimit;
  48898. }
  48899. }
  48900. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48901. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48902. this.beta = this.beta + (2 * Math.PI);
  48903. }
  48904. }
  48905. else {
  48906. if (this.beta > this.upperBetaLimit) {
  48907. this.beta = this.upperBetaLimit;
  48908. }
  48909. }
  48910. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48911. this.alpha = this.lowerAlphaLimit;
  48912. }
  48913. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48914. this.alpha = this.upperAlphaLimit;
  48915. }
  48916. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48917. this.radius = this.lowerRadiusLimit;
  48918. }
  48919. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48920. this.radius = this.upperRadiusLimit;
  48921. }
  48922. };
  48923. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48924. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48925. this.radius = this._computationVector.length();
  48926. if (this.radius === 0) {
  48927. this.radius = 0.0001; // Just to avoid division by zero
  48928. }
  48929. // Alpha
  48930. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48931. if (this._computationVector.z < 0) {
  48932. this.alpha = 2 * Math.PI - this.alpha;
  48933. }
  48934. // Beta
  48935. this.beta = Math.acos(this._computationVector.y / this.radius);
  48936. this._checkLimits();
  48937. };
  48938. ArcRotateCamera.prototype.setPosition = function (position) {
  48939. if (this.position.equals(position)) {
  48940. return;
  48941. }
  48942. this.position.copyFrom(position);
  48943. this.rebuildAnglesAndRadius();
  48944. };
  48945. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48946. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48947. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48948. if (target.getBoundingInfo) {
  48949. if (toBoundingCenter) {
  48950. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48951. }
  48952. else {
  48953. this._targetBoundingCenter = null;
  48954. }
  48955. this._targetHost = target;
  48956. this._target = this._getTargetPosition();
  48957. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48958. }
  48959. else {
  48960. var newTarget = target;
  48961. var currentTarget = this._getTargetPosition();
  48962. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48963. return;
  48964. }
  48965. this._targetHost = null;
  48966. this._target = newTarget;
  48967. this._targetBoundingCenter = null;
  48968. this.onMeshTargetChangedObservable.notifyObservers(null);
  48969. }
  48970. this.rebuildAnglesAndRadius();
  48971. };
  48972. ArcRotateCamera.prototype._getViewMatrix = function () {
  48973. // Compute
  48974. var cosa = Math.cos(this.alpha);
  48975. var sina = Math.sin(this.alpha);
  48976. var cosb = Math.cos(this.beta);
  48977. var sinb = Math.sin(this.beta);
  48978. if (sinb === 0) {
  48979. sinb = 0.0001;
  48980. }
  48981. var target = this._getTargetPosition();
  48982. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48983. target.addToRef(this._computationVector, this._newPosition);
  48984. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48985. if (!this._collider) {
  48986. this._collider = new BABYLON.Collider();
  48987. }
  48988. this._collider._radius = this.collisionRadius;
  48989. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48990. this._collisionTriggered = true;
  48991. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48992. }
  48993. else {
  48994. this.position.copyFrom(this._newPosition);
  48995. var up = this.upVector;
  48996. if (this.allowUpsideDown && sinb < 0) {
  48997. up = up.clone();
  48998. up = up.negate();
  48999. }
  49000. this._computeViewMatrix(this.position, target, up);
  49001. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49002. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49003. }
  49004. this._currentTarget = target;
  49005. return this._viewMatrix;
  49006. };
  49007. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49008. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49009. meshes = meshes || this.getScene().meshes;
  49010. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49011. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49012. this.radius = distance * this.zoomOnFactor;
  49013. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49014. };
  49015. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49016. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49017. var meshesOrMinMaxVector;
  49018. var distance;
  49019. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49020. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49021. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49022. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49023. }
  49024. else { //minMaxVector and distance
  49025. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49026. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49027. distance = minMaxVectorAndDistance.distance;
  49028. }
  49029. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49030. if (!doNotUpdateMaxZ) {
  49031. this.maxZ = distance * 2;
  49032. }
  49033. };
  49034. /**
  49035. * @override
  49036. * Override Camera.createRigCamera
  49037. */
  49038. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49039. var alphaShift = 0;
  49040. switch (this.cameraRigMode) {
  49041. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49042. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49043. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49044. case BABYLON.Camera.RIG_MODE_VR:
  49045. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49046. break;
  49047. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49048. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49049. break;
  49050. }
  49051. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49052. rigCam._cameraRigParams = {};
  49053. return rigCam;
  49054. };
  49055. /**
  49056. * @override
  49057. * Override Camera._updateRigCameras
  49058. */
  49059. ArcRotateCamera.prototype._updateRigCameras = function () {
  49060. var camLeft = this._rigCameras[0];
  49061. var camRight = this._rigCameras[1];
  49062. camLeft.beta = camRight.beta = this.beta;
  49063. camLeft.radius = camRight.radius = this.radius;
  49064. switch (this.cameraRigMode) {
  49065. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49066. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49067. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49068. case BABYLON.Camera.RIG_MODE_VR:
  49069. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49070. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49071. break;
  49072. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49073. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49074. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49075. break;
  49076. }
  49077. _super.prototype._updateRigCameras.call(this);
  49078. };
  49079. ArcRotateCamera.prototype.dispose = function () {
  49080. this.inputs.clear();
  49081. _super.prototype.dispose.call(this);
  49082. };
  49083. ArcRotateCamera.prototype.getClassName = function () {
  49084. return "ArcRotateCamera";
  49085. };
  49086. __decorate([
  49087. BABYLON.serialize()
  49088. ], ArcRotateCamera.prototype, "alpha", void 0);
  49089. __decorate([
  49090. BABYLON.serialize()
  49091. ], ArcRotateCamera.prototype, "beta", void 0);
  49092. __decorate([
  49093. BABYLON.serialize()
  49094. ], ArcRotateCamera.prototype, "radius", void 0);
  49095. __decorate([
  49096. BABYLON.serializeAsVector3("target")
  49097. ], ArcRotateCamera.prototype, "_target", void 0);
  49098. __decorate([
  49099. BABYLON.serialize()
  49100. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49101. __decorate([
  49102. BABYLON.serialize()
  49103. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49104. __decorate([
  49105. BABYLON.serialize()
  49106. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49107. __decorate([
  49108. BABYLON.serialize()
  49109. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49110. __decorate([
  49111. BABYLON.serialize()
  49112. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49113. __decorate([
  49114. BABYLON.serialize()
  49115. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49116. __decorate([
  49117. BABYLON.serialize()
  49118. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49119. __decorate([
  49120. BABYLON.serialize()
  49121. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49122. __decorate([
  49123. BABYLON.serialize()
  49124. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49125. __decorate([
  49126. BABYLON.serialize()
  49127. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49128. __decorate([
  49129. BABYLON.serialize()
  49130. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49131. __decorate([
  49132. BABYLON.serialize()
  49133. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49134. __decorate([
  49135. BABYLON.serialize()
  49136. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49137. __decorate([
  49138. BABYLON.serializeAsVector3()
  49139. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49140. __decorate([
  49141. BABYLON.serialize()
  49142. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49143. __decorate([
  49144. BABYLON.serialize()
  49145. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49146. __decorate([
  49147. BABYLON.serialize()
  49148. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49149. return ArcRotateCamera;
  49150. }(BABYLON.TargetCamera));
  49151. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49152. })(BABYLON || (BABYLON = {}));
  49153. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49154. var BABYLON;
  49155. (function (BABYLON) {
  49156. /**
  49157. * The HemisphericLight simulates the ambient environment light,
  49158. * so the passed direction is the light reflection direction, not the incoming direction.
  49159. */
  49160. var HemisphericLight = /** @class */ (function (_super) {
  49161. __extends(HemisphericLight, _super);
  49162. /**
  49163. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49164. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49165. * The HemisphericLight can't cast shadows.
  49166. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49167. * @param name The friendly name of the light
  49168. * @param direction The direction of the light reflection
  49169. * @param scene The scene the light belongs to
  49170. */
  49171. function HemisphericLight(name, direction, scene) {
  49172. var _this = _super.call(this, name, scene) || this;
  49173. /**
  49174. * The groundColor is the light in the opposite direction to the one specified during creation.
  49175. * 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.
  49176. */
  49177. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49178. _this.direction = direction || BABYLON.Vector3.Up();
  49179. return _this;
  49180. }
  49181. HemisphericLight.prototype._buildUniformLayout = function () {
  49182. this._uniformBuffer.addUniform("vLightData", 4);
  49183. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49184. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49185. this._uniformBuffer.addUniform("vLightGround", 3);
  49186. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49187. this._uniformBuffer.addUniform("depthValues", 2);
  49188. this._uniformBuffer.create();
  49189. };
  49190. /**
  49191. * Returns the string "HemisphericLight".
  49192. * @return The class name
  49193. */
  49194. HemisphericLight.prototype.getClassName = function () {
  49195. return "HemisphericLight";
  49196. };
  49197. /**
  49198. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49199. * Returns the updated direction.
  49200. * @param target The target the direction should point to
  49201. * @return The computed direction
  49202. */
  49203. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49204. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49205. return this.direction;
  49206. };
  49207. /**
  49208. * Returns the shadow generator associated to the light.
  49209. * @returns Always null for hemispheric lights because it does not support shadows.
  49210. */
  49211. HemisphericLight.prototype.getShadowGenerator = function () {
  49212. return null;
  49213. };
  49214. /**
  49215. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49216. * @param effect The effect to update
  49217. * @param lightIndex The index of the light in the effect to update
  49218. * @returns The hemispheric light
  49219. */
  49220. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49221. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49222. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49223. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49224. return this;
  49225. };
  49226. /**
  49227. * @hidden internal use only.
  49228. */
  49229. HemisphericLight.prototype._getWorldMatrix = function () {
  49230. if (!this._worldMatrix) {
  49231. this._worldMatrix = BABYLON.Matrix.Identity();
  49232. }
  49233. return this._worldMatrix;
  49234. };
  49235. /**
  49236. * Returns the integer 3.
  49237. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49238. */
  49239. HemisphericLight.prototype.getTypeID = function () {
  49240. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49241. };
  49242. __decorate([
  49243. BABYLON.serializeAsColor3()
  49244. ], HemisphericLight.prototype, "groundColor", void 0);
  49245. __decorate([
  49246. BABYLON.serializeAsVector3()
  49247. ], HemisphericLight.prototype, "direction", void 0);
  49248. return HemisphericLight;
  49249. }(BABYLON.Light));
  49250. BABYLON.HemisphericLight = HemisphericLight;
  49251. })(BABYLON || (BABYLON = {}));
  49252. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49253. var BABYLON;
  49254. (function (BABYLON) {
  49255. /**
  49256. * Base implementation IShadowLight
  49257. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49258. */
  49259. var ShadowLight = /** @class */ (function (_super) {
  49260. __extends(ShadowLight, _super);
  49261. function ShadowLight() {
  49262. var _this = _super !== null && _super.apply(this, arguments) || this;
  49263. _this._needProjectionMatrixCompute = true;
  49264. return _this;
  49265. }
  49266. ShadowLight.prototype._setPosition = function (value) {
  49267. this._position = value;
  49268. };
  49269. Object.defineProperty(ShadowLight.prototype, "position", {
  49270. /**
  49271. * Sets the position the shadow will be casted from. Also use as the light position for both
  49272. * point and spot lights.
  49273. */
  49274. get: function () {
  49275. return this._position;
  49276. },
  49277. /**
  49278. * Sets the position the shadow will be casted from. Also use as the light position for both
  49279. * point and spot lights.
  49280. */
  49281. set: function (value) {
  49282. this._setPosition(value);
  49283. },
  49284. enumerable: true,
  49285. configurable: true
  49286. });
  49287. ShadowLight.prototype._setDirection = function (value) {
  49288. this._direction = value;
  49289. };
  49290. Object.defineProperty(ShadowLight.prototype, "direction", {
  49291. /**
  49292. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49293. * Also use as the light direction on spot and directional lights.
  49294. */
  49295. get: function () {
  49296. return this._direction;
  49297. },
  49298. /**
  49299. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49300. * Also use as the light direction on spot and directional lights.
  49301. */
  49302. set: function (value) {
  49303. this._setDirection(value);
  49304. },
  49305. enumerable: true,
  49306. configurable: true
  49307. });
  49308. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49309. /**
  49310. * Gets the shadow projection clipping minimum z value.
  49311. */
  49312. get: function () {
  49313. return this._shadowMinZ;
  49314. },
  49315. /**
  49316. * Sets the shadow projection clipping minimum z value.
  49317. */
  49318. set: function (value) {
  49319. this._shadowMinZ = value;
  49320. this.forceProjectionMatrixCompute();
  49321. },
  49322. enumerable: true,
  49323. configurable: true
  49324. });
  49325. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49326. /**
  49327. * Sets the shadow projection clipping maximum z value.
  49328. */
  49329. get: function () {
  49330. return this._shadowMaxZ;
  49331. },
  49332. /**
  49333. * Gets the shadow projection clipping maximum z value.
  49334. */
  49335. set: function (value) {
  49336. this._shadowMaxZ = value;
  49337. this.forceProjectionMatrixCompute();
  49338. },
  49339. enumerable: true,
  49340. configurable: true
  49341. });
  49342. /**
  49343. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49344. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49345. */
  49346. ShadowLight.prototype.computeTransformedInformation = function () {
  49347. if (this.parent && this.parent.getWorldMatrix) {
  49348. if (!this.transformedPosition) {
  49349. this.transformedPosition = BABYLON.Vector3.Zero();
  49350. }
  49351. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49352. // In case the direction is present.
  49353. if (this.direction) {
  49354. if (!this.transformedDirection) {
  49355. this.transformedDirection = BABYLON.Vector3.Zero();
  49356. }
  49357. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49358. }
  49359. return true;
  49360. }
  49361. return false;
  49362. };
  49363. /**
  49364. * Return the depth scale used for the shadow map.
  49365. * @returns the depth scale.
  49366. */
  49367. ShadowLight.prototype.getDepthScale = function () {
  49368. return 50.0;
  49369. };
  49370. /**
  49371. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49372. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49373. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49374. */
  49375. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49376. return this.transformedDirection ? this.transformedDirection : this.direction;
  49377. };
  49378. /**
  49379. * Returns the ShadowLight absolute position in the World.
  49380. * @returns the position vector in world space
  49381. */
  49382. ShadowLight.prototype.getAbsolutePosition = function () {
  49383. return this.transformedPosition ? this.transformedPosition : this.position;
  49384. };
  49385. /**
  49386. * Sets the ShadowLight direction toward the passed target.
  49387. * @param target The point tot target in local space
  49388. * @returns the updated ShadowLight direction
  49389. */
  49390. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49391. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49392. return this.direction;
  49393. };
  49394. /**
  49395. * Returns the light rotation in euler definition.
  49396. * @returns the x y z rotation in local space.
  49397. */
  49398. ShadowLight.prototype.getRotation = function () {
  49399. this.direction.normalize();
  49400. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49401. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49402. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49403. };
  49404. /**
  49405. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49406. * @returns true if a cube texture needs to be use
  49407. */
  49408. ShadowLight.prototype.needCube = function () {
  49409. return false;
  49410. };
  49411. /**
  49412. * Detects if the projection matrix requires to be recomputed this frame.
  49413. * @returns true if it requires to be recomputed otherwise, false.
  49414. */
  49415. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49416. return this._needProjectionMatrixCompute;
  49417. };
  49418. /**
  49419. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49420. */
  49421. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49422. this._needProjectionMatrixCompute = true;
  49423. };
  49424. /**
  49425. * Get the world matrix of the sahdow lights.
  49426. * @hidden Internal Use Only
  49427. */
  49428. ShadowLight.prototype._getWorldMatrix = function () {
  49429. if (!this._worldMatrix) {
  49430. this._worldMatrix = BABYLON.Matrix.Identity();
  49431. }
  49432. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49433. return this._worldMatrix;
  49434. };
  49435. /**
  49436. * Gets the minZ used for shadow according to both the scene and the light.
  49437. * @param activeCamera The camera we are returning the min for
  49438. * @returns the depth min z
  49439. */
  49440. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49441. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49442. };
  49443. /**
  49444. * Gets the maxZ used for shadow according to both the scene and the light.
  49445. * @param activeCamera The camera we are returning the max for
  49446. * @returns the depth max z
  49447. */
  49448. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49449. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49450. };
  49451. /**
  49452. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49453. * @param matrix The materix to updated with the projection information
  49454. * @param viewMatrix The transform matrix of the light
  49455. * @param renderList The list of mesh to render in the map
  49456. * @returns The current light
  49457. */
  49458. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49459. if (this.customProjectionMatrixBuilder) {
  49460. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49461. }
  49462. else {
  49463. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49464. }
  49465. return this;
  49466. };
  49467. __decorate([
  49468. BABYLON.serializeAsVector3()
  49469. ], ShadowLight.prototype, "position", null);
  49470. __decorate([
  49471. BABYLON.serializeAsVector3()
  49472. ], ShadowLight.prototype, "direction", null);
  49473. __decorate([
  49474. BABYLON.serialize()
  49475. ], ShadowLight.prototype, "shadowMinZ", null);
  49476. __decorate([
  49477. BABYLON.serialize()
  49478. ], ShadowLight.prototype, "shadowMaxZ", null);
  49479. return ShadowLight;
  49480. }(BABYLON.Light));
  49481. BABYLON.ShadowLight = ShadowLight;
  49482. })(BABYLON || (BABYLON = {}));
  49483. //# sourceMappingURL=babylon.shadowLight.js.map
  49484. var BABYLON;
  49485. (function (BABYLON) {
  49486. /**
  49487. * A point light is a light defined by an unique point in world space.
  49488. * The light is emitted in every direction from this point.
  49489. * A good example of a point light is a standard light bulb.
  49490. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49491. */
  49492. var PointLight = /** @class */ (function (_super) {
  49493. __extends(PointLight, _super);
  49494. /**
  49495. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49496. * A PointLight emits the light in every direction.
  49497. * It can cast shadows.
  49498. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49499. * ```javascript
  49500. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49501. * ```
  49502. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49503. * @param name The light friendly name
  49504. * @param position The position of the point light in the scene
  49505. * @param scene The scene the lights belongs to
  49506. */
  49507. function PointLight(name, position, scene) {
  49508. var _this = _super.call(this, name, scene) || this;
  49509. _this._shadowAngle = Math.PI / 2;
  49510. _this.position = position;
  49511. return _this;
  49512. }
  49513. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49514. /**
  49515. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49516. * This specifies what angle the shadow will use to be created.
  49517. *
  49518. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49519. */
  49520. get: function () {
  49521. return this._shadowAngle;
  49522. },
  49523. /**
  49524. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49525. * This specifies what angle the shadow will use to be created.
  49526. *
  49527. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49528. */
  49529. set: function (value) {
  49530. this._shadowAngle = value;
  49531. this.forceProjectionMatrixCompute();
  49532. },
  49533. enumerable: true,
  49534. configurable: true
  49535. });
  49536. Object.defineProperty(PointLight.prototype, "direction", {
  49537. /**
  49538. * Gets the direction if it has been set.
  49539. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49540. */
  49541. get: function () {
  49542. return this._direction;
  49543. },
  49544. /**
  49545. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49546. */
  49547. set: function (value) {
  49548. var previousNeedCube = this.needCube();
  49549. this._direction = value;
  49550. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49551. this._shadowGenerator.recreateShadowMap();
  49552. }
  49553. },
  49554. enumerable: true,
  49555. configurable: true
  49556. });
  49557. /**
  49558. * Returns the string "PointLight"
  49559. * @returns the class name
  49560. */
  49561. PointLight.prototype.getClassName = function () {
  49562. return "PointLight";
  49563. };
  49564. /**
  49565. * Returns the integer 0.
  49566. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49567. */
  49568. PointLight.prototype.getTypeID = function () {
  49569. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49570. };
  49571. /**
  49572. * Specifies wether or not the shadowmap should be a cube texture.
  49573. * @returns true if the shadowmap needs to be a cube texture.
  49574. */
  49575. PointLight.prototype.needCube = function () {
  49576. return !this.direction;
  49577. };
  49578. /**
  49579. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49580. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49581. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49582. */
  49583. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49584. if (this.direction) {
  49585. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49586. }
  49587. else {
  49588. switch (faceIndex) {
  49589. case 0:
  49590. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49591. case 1:
  49592. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49593. case 2:
  49594. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49595. case 3:
  49596. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49597. case 4:
  49598. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49599. case 5:
  49600. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49601. }
  49602. }
  49603. return BABYLON.Vector3.Zero();
  49604. };
  49605. /**
  49606. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49607. * - fov = PI / 2
  49608. * - aspect ratio : 1.0
  49609. * - z-near and far equal to the active camera minZ and maxZ.
  49610. * Returns the PointLight.
  49611. */
  49612. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49613. var activeCamera = this.getScene().activeCamera;
  49614. if (!activeCamera) {
  49615. return;
  49616. }
  49617. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49618. };
  49619. PointLight.prototype._buildUniformLayout = function () {
  49620. this._uniformBuffer.addUniform("vLightData", 4);
  49621. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49622. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49623. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49624. this._uniformBuffer.addUniform("depthValues", 2);
  49625. this._uniformBuffer.create();
  49626. };
  49627. /**
  49628. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49629. * @param effect The effect to update
  49630. * @param lightIndex The index of the light in the effect to update
  49631. * @returns The point light
  49632. */
  49633. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49634. if (this.computeTransformedInformation()) {
  49635. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49636. return this;
  49637. }
  49638. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49639. return this;
  49640. };
  49641. __decorate([
  49642. BABYLON.serialize()
  49643. ], PointLight.prototype, "shadowAngle", null);
  49644. return PointLight;
  49645. }(BABYLON.ShadowLight));
  49646. BABYLON.PointLight = PointLight;
  49647. })(BABYLON || (BABYLON = {}));
  49648. //# sourceMappingURL=babylon.pointLight.js.map
  49649. var BABYLON;
  49650. (function (BABYLON) {
  49651. /**
  49652. * A directional light is defined by a direction (what a surprise!).
  49653. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49654. * 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.
  49655. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49656. */
  49657. var DirectionalLight = /** @class */ (function (_super) {
  49658. __extends(DirectionalLight, _super);
  49659. /**
  49660. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49661. * The directional light is emitted from everywhere in the given direction.
  49662. * It can cast shawdows.
  49663. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49664. * @param name The friendly name of the light
  49665. * @param direction The direction of the light
  49666. * @param scene The scene the light belongs to
  49667. */
  49668. function DirectionalLight(name, direction, scene) {
  49669. var _this = _super.call(this, name, scene) || this;
  49670. _this._shadowFrustumSize = 0;
  49671. _this._shadowOrthoScale = 0.1;
  49672. /**
  49673. * Automatically compute the projection matrix to best fit (including all the casters)
  49674. * on each frame.
  49675. */
  49676. _this.autoUpdateExtends = true;
  49677. // Cache
  49678. _this._orthoLeft = Number.MAX_VALUE;
  49679. _this._orthoRight = Number.MIN_VALUE;
  49680. _this._orthoTop = Number.MIN_VALUE;
  49681. _this._orthoBottom = Number.MAX_VALUE;
  49682. _this.position = direction.scale(-1.0);
  49683. _this.direction = direction;
  49684. return _this;
  49685. }
  49686. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49687. /**
  49688. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49689. */
  49690. get: function () {
  49691. return this._shadowFrustumSize;
  49692. },
  49693. /**
  49694. * Specifies a fix frustum size for the shadow generation.
  49695. */
  49696. set: function (value) {
  49697. this._shadowFrustumSize = value;
  49698. this.forceProjectionMatrixCompute();
  49699. },
  49700. enumerable: true,
  49701. configurable: true
  49702. });
  49703. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49704. /**
  49705. * Gets the shadow projection scale against the optimal computed one.
  49706. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49707. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49708. */
  49709. get: function () {
  49710. return this._shadowOrthoScale;
  49711. },
  49712. /**
  49713. * Sets the shadow projection scale against the optimal computed one.
  49714. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49715. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49716. */
  49717. set: function (value) {
  49718. this._shadowOrthoScale = value;
  49719. this.forceProjectionMatrixCompute();
  49720. },
  49721. enumerable: true,
  49722. configurable: true
  49723. });
  49724. /**
  49725. * Returns the string "DirectionalLight".
  49726. * @return The class name
  49727. */
  49728. DirectionalLight.prototype.getClassName = function () {
  49729. return "DirectionalLight";
  49730. };
  49731. /**
  49732. * Returns the integer 1.
  49733. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49734. */
  49735. DirectionalLight.prototype.getTypeID = function () {
  49736. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49737. };
  49738. /**
  49739. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49740. * Returns the DirectionalLight Shadow projection matrix.
  49741. */
  49742. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49743. if (this.shadowFrustumSize > 0) {
  49744. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49745. }
  49746. else {
  49747. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49748. }
  49749. };
  49750. /**
  49751. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49752. * Returns the DirectionalLight Shadow projection matrix.
  49753. */
  49754. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49755. var activeCamera = this.getScene().activeCamera;
  49756. if (!activeCamera) {
  49757. return;
  49758. }
  49759. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49760. };
  49761. /**
  49762. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49763. * Returns the DirectionalLight Shadow projection matrix.
  49764. */
  49765. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49766. var activeCamera = this.getScene().activeCamera;
  49767. if (!activeCamera) {
  49768. return;
  49769. }
  49770. // Check extends
  49771. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49772. var tempVector3 = BABYLON.Vector3.Zero();
  49773. this._orthoLeft = Number.MAX_VALUE;
  49774. this._orthoRight = Number.MIN_VALUE;
  49775. this._orthoTop = Number.MIN_VALUE;
  49776. this._orthoBottom = Number.MAX_VALUE;
  49777. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49778. var mesh = renderList[meshIndex];
  49779. if (!mesh) {
  49780. continue;
  49781. }
  49782. var boundingInfo = mesh.getBoundingInfo();
  49783. var boundingBox = boundingInfo.boundingBox;
  49784. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49785. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49786. if (tempVector3.x < this._orthoLeft)
  49787. this._orthoLeft = tempVector3.x;
  49788. if (tempVector3.y < this._orthoBottom)
  49789. this._orthoBottom = tempVector3.y;
  49790. if (tempVector3.x > this._orthoRight)
  49791. this._orthoRight = tempVector3.x;
  49792. if (tempVector3.y > this._orthoTop)
  49793. this._orthoTop = tempVector3.y;
  49794. }
  49795. }
  49796. }
  49797. var xOffset = this._orthoRight - this._orthoLeft;
  49798. var yOffset = this._orthoTop - this._orthoBottom;
  49799. 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);
  49800. };
  49801. DirectionalLight.prototype._buildUniformLayout = function () {
  49802. this._uniformBuffer.addUniform("vLightData", 4);
  49803. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49804. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49805. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49806. this._uniformBuffer.addUniform("depthValues", 2);
  49807. this._uniformBuffer.create();
  49808. };
  49809. /**
  49810. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49811. * @param effect The effect to update
  49812. * @param lightIndex The index of the light in the effect to update
  49813. * @returns The directional light
  49814. */
  49815. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49816. if (this.computeTransformedInformation()) {
  49817. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49818. return this;
  49819. }
  49820. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49821. return this;
  49822. };
  49823. /**
  49824. * Gets the minZ used for shadow according to both the scene and the light.
  49825. *
  49826. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49827. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49828. * @param activeCamera The camera we are returning the min for
  49829. * @returns the depth min z
  49830. */
  49831. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49832. return 1;
  49833. };
  49834. /**
  49835. * Gets the maxZ used for shadow according to both the scene and the light.
  49836. *
  49837. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49838. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49839. * @param activeCamera The camera we are returning the max for
  49840. * @returns the depth max z
  49841. */
  49842. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49843. return 1;
  49844. };
  49845. __decorate([
  49846. BABYLON.serialize()
  49847. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49848. __decorate([
  49849. BABYLON.serialize()
  49850. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49851. __decorate([
  49852. BABYLON.serialize()
  49853. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49854. return DirectionalLight;
  49855. }(BABYLON.ShadowLight));
  49856. BABYLON.DirectionalLight = DirectionalLight;
  49857. })(BABYLON || (BABYLON = {}));
  49858. //# sourceMappingURL=babylon.directionalLight.js.map
  49859. var BABYLON;
  49860. (function (BABYLON) {
  49861. /**
  49862. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49863. * These values define a cone of light starting from the position, emitting toward the direction.
  49864. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49865. * and the exponent defines the speed of the decay of the light with distance (reach).
  49866. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49867. */
  49868. var SpotLight = /** @class */ (function (_super) {
  49869. __extends(SpotLight, _super);
  49870. /**
  49871. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49872. * It can cast shadows.
  49873. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49874. * @param name The light friendly name
  49875. * @param position The position of the spot light in the scene
  49876. * @param direction The direction of the light in the scene
  49877. * @param angle The cone angle of the light in Radians
  49878. * @param exponent The light decay speed with the distance from the emission spot
  49879. * @param scene The scene the lights belongs to
  49880. */
  49881. function SpotLight(name, position, direction, angle, exponent, scene) {
  49882. var _this = _super.call(this, name, scene) || this;
  49883. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49884. _this._projectionTextureLightNear = 1e-6;
  49885. _this._projectionTextureLightFar = 1000.0;
  49886. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49887. _this._projectionTextureViewLightDirty = true;
  49888. _this._projectionTextureProjectionLightDirty = true;
  49889. _this._projectionTextureDirty = true;
  49890. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49891. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49892. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49893. _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);
  49894. _this.position = position;
  49895. _this.direction = direction;
  49896. _this.angle = angle;
  49897. _this.exponent = exponent;
  49898. return _this;
  49899. }
  49900. Object.defineProperty(SpotLight.prototype, "angle", {
  49901. /**
  49902. * Gets the cone angle of the spot light in Radians.
  49903. */
  49904. get: function () {
  49905. return this._angle;
  49906. },
  49907. /**
  49908. * Sets the cone angle of the spot light in Radians.
  49909. */
  49910. set: function (value) {
  49911. this._angle = value;
  49912. this._projectionTextureProjectionLightDirty = true;
  49913. this.forceProjectionMatrixCompute();
  49914. },
  49915. enumerable: true,
  49916. configurable: true
  49917. });
  49918. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49919. /**
  49920. * Allows scaling the angle of the light for shadow generation only.
  49921. */
  49922. get: function () {
  49923. return this._shadowAngleScale;
  49924. },
  49925. /**
  49926. * Allows scaling the angle of the light for shadow generation only.
  49927. */
  49928. set: function (value) {
  49929. this._shadowAngleScale = value;
  49930. this.forceProjectionMatrixCompute();
  49931. },
  49932. enumerable: true,
  49933. configurable: true
  49934. });
  49935. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49936. /**
  49937. * Allows reading the projecton texture
  49938. */
  49939. get: function () {
  49940. return this._projectionTextureMatrix;
  49941. },
  49942. enumerable: true,
  49943. configurable: true
  49944. });
  49945. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49946. /**
  49947. * Gets the near clip of the Spotlight for texture projection.
  49948. */
  49949. get: function () {
  49950. return this._projectionTextureLightNear;
  49951. },
  49952. /**
  49953. * Sets the near clip of the Spotlight for texture projection.
  49954. */
  49955. set: function (value) {
  49956. this._projectionTextureLightNear = value;
  49957. this._projectionTextureProjectionLightDirty = true;
  49958. },
  49959. enumerable: true,
  49960. configurable: true
  49961. });
  49962. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49963. /**
  49964. * Gets the far clip of the Spotlight for texture projection.
  49965. */
  49966. get: function () {
  49967. return this._projectionTextureLightFar;
  49968. },
  49969. /**
  49970. * Sets the far clip of the Spotlight for texture projection.
  49971. */
  49972. set: function (value) {
  49973. this._projectionTextureLightFar = value;
  49974. this._projectionTextureProjectionLightDirty = true;
  49975. },
  49976. enumerable: true,
  49977. configurable: true
  49978. });
  49979. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49980. /**
  49981. * Gets the Up vector of the Spotlight for texture projection.
  49982. */
  49983. get: function () {
  49984. return this._projectionTextureUpDirection;
  49985. },
  49986. /**
  49987. * Sets the Up vector of the Spotlight for texture projection.
  49988. */
  49989. set: function (value) {
  49990. this._projectionTextureUpDirection = value;
  49991. this._projectionTextureProjectionLightDirty = true;
  49992. },
  49993. enumerable: true,
  49994. configurable: true
  49995. });
  49996. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49997. /**
  49998. * Gets the projection texture of the light.
  49999. */
  50000. get: function () {
  50001. return this._projectionTexture;
  50002. },
  50003. /**
  50004. * Sets the projection texture of the light.
  50005. */
  50006. set: function (value) {
  50007. this._projectionTexture = value;
  50008. this._projectionTextureDirty = true;
  50009. },
  50010. enumerable: true,
  50011. configurable: true
  50012. });
  50013. /**
  50014. * Returns the string "SpotLight".
  50015. * @returns the class name
  50016. */
  50017. SpotLight.prototype.getClassName = function () {
  50018. return "SpotLight";
  50019. };
  50020. /**
  50021. * Returns the integer 2.
  50022. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50023. */
  50024. SpotLight.prototype.getTypeID = function () {
  50025. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50026. };
  50027. /**
  50028. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50029. */
  50030. SpotLight.prototype._setDirection = function (value) {
  50031. _super.prototype._setDirection.call(this, value);
  50032. this._projectionTextureViewLightDirty = true;
  50033. };
  50034. /**
  50035. * Overrides the position setter to recompute the projection texture view light Matrix.
  50036. */
  50037. SpotLight.prototype._setPosition = function (value) {
  50038. _super.prototype._setPosition.call(this, value);
  50039. this._projectionTextureViewLightDirty = true;
  50040. };
  50041. /**
  50042. * 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.
  50043. * Returns the SpotLight.
  50044. */
  50045. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50046. var activeCamera = this.getScene().activeCamera;
  50047. if (!activeCamera) {
  50048. return;
  50049. }
  50050. this._shadowAngleScale = this._shadowAngleScale || 1;
  50051. var angle = this._shadowAngleScale * this._angle;
  50052. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50053. };
  50054. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50055. this._projectionTextureViewLightDirty = false;
  50056. this._projectionTextureDirty = true;
  50057. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50058. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50059. };
  50060. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50061. this._projectionTextureProjectionLightDirty = false;
  50062. this._projectionTextureDirty = true;
  50063. var light_far = this.projectionTextureLightFar;
  50064. var light_near = this.projectionTextureLightNear;
  50065. var P = light_far / (light_far - light_near);
  50066. var Q = -P * light_near;
  50067. var S = 1.0 / Math.tan(this._angle / 2.0);
  50068. var A = 1.0;
  50069. 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);
  50070. };
  50071. /**
  50072. * Main function for light texture projection matrix computing.
  50073. */
  50074. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50075. this._projectionTextureDirty = false;
  50076. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50077. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50078. };
  50079. SpotLight.prototype._buildUniformLayout = function () {
  50080. this._uniformBuffer.addUniform("vLightData", 4);
  50081. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50082. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50083. this._uniformBuffer.addUniform("vLightDirection", 3);
  50084. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50085. this._uniformBuffer.addUniform("depthValues", 2);
  50086. this._uniformBuffer.create();
  50087. };
  50088. /**
  50089. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50090. * @param effect The effect to update
  50091. * @param lightIndex The index of the light in the effect to update
  50092. * @returns The spot light
  50093. */
  50094. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50095. var normalizeDirection;
  50096. if (this.computeTransformedInformation()) {
  50097. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50098. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50099. }
  50100. else {
  50101. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50102. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50103. }
  50104. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50105. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50106. if (this._projectionTextureViewLightDirty) {
  50107. this._computeProjectionTextureViewLightMatrix();
  50108. }
  50109. if (this._projectionTextureProjectionLightDirty) {
  50110. this._computeProjectionTextureProjectionLightMatrix();
  50111. }
  50112. if (this._projectionTextureDirty) {
  50113. this._computeProjectionTextureMatrix();
  50114. }
  50115. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50116. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50117. }
  50118. return this;
  50119. };
  50120. /**
  50121. * Disposes the light and the associated resources.
  50122. */
  50123. SpotLight.prototype.dispose = function () {
  50124. _super.prototype.dispose.call(this);
  50125. if (this._projectionTexture) {
  50126. this._projectionTexture.dispose();
  50127. }
  50128. };
  50129. __decorate([
  50130. BABYLON.serialize()
  50131. ], SpotLight.prototype, "angle", null);
  50132. __decorate([
  50133. BABYLON.serialize()
  50134. ], SpotLight.prototype, "shadowAngleScale", null);
  50135. __decorate([
  50136. BABYLON.serialize()
  50137. ], SpotLight.prototype, "exponent", void 0);
  50138. __decorate([
  50139. BABYLON.serialize()
  50140. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50141. __decorate([
  50142. BABYLON.serialize()
  50143. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50144. __decorate([
  50145. BABYLON.serialize()
  50146. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50147. __decorate([
  50148. BABYLON.serializeAsTexture("projectedLightTexture")
  50149. ], SpotLight.prototype, "_projectionTexture", void 0);
  50150. return SpotLight;
  50151. }(BABYLON.ShadowLight));
  50152. BABYLON.SpotLight = SpotLight;
  50153. })(BABYLON || (BABYLON = {}));
  50154. //# sourceMappingURL=babylon.spotLight.js.map
  50155. var BABYLON;
  50156. (function (BABYLON) {
  50157. /**
  50158. * Class used to override all child animations of a given target
  50159. */
  50160. var AnimationPropertiesOverride = /** @class */ (function () {
  50161. function AnimationPropertiesOverride() {
  50162. /**
  50163. * Gets or sets a value indicating if animation blending must be used
  50164. */
  50165. this.enableBlending = false;
  50166. /**
  50167. * Gets or sets the blending speed to use when enableBlending is true
  50168. */
  50169. this.blendingSpeed = 0.01;
  50170. /**
  50171. * Gets or sets the default loop mode to use
  50172. */
  50173. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50174. }
  50175. return AnimationPropertiesOverride;
  50176. }());
  50177. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50178. })(BABYLON || (BABYLON = {}));
  50179. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50180. var BABYLON;
  50181. (function (BABYLON) {
  50182. /**
  50183. * Represents the range of an animation
  50184. */
  50185. var AnimationRange = /** @class */ (function () {
  50186. /**
  50187. * Initializes the range of an animation
  50188. * @param name The name of the animation range
  50189. * @param from The starting frame of the animation
  50190. * @param to The ending frame of the animation
  50191. */
  50192. function AnimationRange(
  50193. /**The name of the animation range**/
  50194. name,
  50195. /**The starting frame of the animation */
  50196. from,
  50197. /**The ending frame of the animation*/
  50198. to) {
  50199. this.name = name;
  50200. this.from = from;
  50201. this.to = to;
  50202. }
  50203. /**
  50204. * Makes a copy of the animation range
  50205. * @returns A copy of the animation range
  50206. */
  50207. AnimationRange.prototype.clone = function () {
  50208. return new AnimationRange(this.name, this.from, this.to);
  50209. };
  50210. return AnimationRange;
  50211. }());
  50212. BABYLON.AnimationRange = AnimationRange;
  50213. /**
  50214. * Composed of a frame, and an action function
  50215. */
  50216. var AnimationEvent = /** @class */ (function () {
  50217. /**
  50218. * Initializes the animation event
  50219. * @param frame The frame for which the event is triggered
  50220. * @param action The event to perform when triggered
  50221. * @param onlyOnce Specifies if the event should be triggered only once
  50222. */
  50223. function AnimationEvent(
  50224. /** The frame for which the event is triggered **/
  50225. frame,
  50226. /** The event to perform when triggered **/
  50227. action,
  50228. /** Specifies if the event should be triggered only once**/
  50229. onlyOnce) {
  50230. this.frame = frame;
  50231. this.action = action;
  50232. this.onlyOnce = onlyOnce;
  50233. /**
  50234. * Specifies if the animation event is done
  50235. */
  50236. this.isDone = false;
  50237. }
  50238. return AnimationEvent;
  50239. }());
  50240. BABYLON.AnimationEvent = AnimationEvent;
  50241. /**
  50242. * A cursor which tracks a point on a path
  50243. */
  50244. var PathCursor = /** @class */ (function () {
  50245. /**
  50246. * Initializes the path cursor
  50247. * @param path The path to track
  50248. */
  50249. function PathCursor(path) {
  50250. this.path = path;
  50251. /**
  50252. * Stores path cursor callbacks for when an onchange event is triggered
  50253. */
  50254. this._onchange = new Array();
  50255. /**
  50256. * The value of the path cursor
  50257. */
  50258. this.value = 0;
  50259. /**
  50260. * The animation array of the path cursor
  50261. */
  50262. this.animations = new Array();
  50263. }
  50264. /**
  50265. * Gets the cursor point on the path
  50266. * @returns A point on the path cursor at the cursor location
  50267. */
  50268. PathCursor.prototype.getPoint = function () {
  50269. var point = this.path.getPointAtLengthPosition(this.value);
  50270. return new BABYLON.Vector3(point.x, 0, point.y);
  50271. };
  50272. /**
  50273. * Moves the cursor ahead by the step amount
  50274. * @param step The amount to move the cursor forward
  50275. * @returns This path cursor
  50276. */
  50277. PathCursor.prototype.moveAhead = function (step) {
  50278. if (step === void 0) { step = 0.002; }
  50279. this.move(step);
  50280. return this;
  50281. };
  50282. /**
  50283. * Moves the cursor behind by the step amount
  50284. * @param step The amount to move the cursor back
  50285. * @returns This path cursor
  50286. */
  50287. PathCursor.prototype.moveBack = function (step) {
  50288. if (step === void 0) { step = 0.002; }
  50289. this.move(-step);
  50290. return this;
  50291. };
  50292. /**
  50293. * Moves the cursor by the step amount
  50294. * If the step amount is greater than one, an exception is thrown
  50295. * @param step The amount to move the cursor
  50296. * @returns This path cursor
  50297. */
  50298. PathCursor.prototype.move = function (step) {
  50299. if (Math.abs(step) > 1) {
  50300. throw "step size should be less than 1.";
  50301. }
  50302. this.value += step;
  50303. this.ensureLimits();
  50304. this.raiseOnChange();
  50305. return this;
  50306. };
  50307. /**
  50308. * Ensures that the value is limited between zero and one
  50309. * @returns This path cursor
  50310. */
  50311. PathCursor.prototype.ensureLimits = function () {
  50312. while (this.value > 1) {
  50313. this.value -= 1;
  50314. }
  50315. while (this.value < 0) {
  50316. this.value += 1;
  50317. }
  50318. return this;
  50319. };
  50320. /**
  50321. * Runs onchange callbacks on change (used by the animation engine)
  50322. * @returns This path cursor
  50323. */
  50324. PathCursor.prototype.raiseOnChange = function () {
  50325. var _this = this;
  50326. this._onchange.forEach(function (f) { return f(_this); });
  50327. return this;
  50328. };
  50329. /**
  50330. * Executes a function on change
  50331. * @param f A path cursor onchange callback
  50332. * @returns This path cursor
  50333. */
  50334. PathCursor.prototype.onchange = function (f) {
  50335. this._onchange.push(f);
  50336. return this;
  50337. };
  50338. return PathCursor;
  50339. }());
  50340. BABYLON.PathCursor = PathCursor;
  50341. /**
  50342. * Enum for the animation key frame interpolation type
  50343. */
  50344. var AnimationKeyInterpolation;
  50345. (function (AnimationKeyInterpolation) {
  50346. /**
  50347. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50348. */
  50349. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50350. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50351. /**
  50352. * Class used to store any kind of animation
  50353. */
  50354. var Animation = /** @class */ (function () {
  50355. /**
  50356. * Initializes the animation
  50357. * @param name Name of the animation
  50358. * @param targetProperty Property to animate
  50359. * @param framePerSecond The frames per second of the animation
  50360. * @param dataType The data type of the animation
  50361. * @param loopMode The loop mode of the animation
  50362. * @param enableBlendings Specifies if blending should be enabled
  50363. */
  50364. function Animation(
  50365. /**Name of the animation */
  50366. name,
  50367. /**Property to animate */
  50368. targetProperty,
  50369. /**The frames per second of the animation */
  50370. framePerSecond,
  50371. /**The data type of the animation */
  50372. dataType,
  50373. /**The loop mode of the animation */
  50374. loopMode,
  50375. /**Specifies if blending should be enabled */
  50376. enableBlending) {
  50377. this.name = name;
  50378. this.targetProperty = targetProperty;
  50379. this.framePerSecond = framePerSecond;
  50380. this.dataType = dataType;
  50381. this.loopMode = loopMode;
  50382. this.enableBlending = enableBlending;
  50383. /**
  50384. * @hidden Internal use only
  50385. */
  50386. this._runtimeAnimations = new Array();
  50387. /**
  50388. * The set of event that will be linked to this animation
  50389. */
  50390. this._events = new Array();
  50391. /**
  50392. * Stores the blending speed of the animation
  50393. */
  50394. this.blendingSpeed = 0.01;
  50395. /**
  50396. * Stores the animation ranges for the animation
  50397. */
  50398. this._ranges = {};
  50399. this.targetPropertyPath = targetProperty.split(".");
  50400. this.dataType = dataType;
  50401. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50402. }
  50403. /**
  50404. * @hidden Internal use
  50405. */
  50406. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50407. var dataType = undefined;
  50408. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50409. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50410. }
  50411. else if (from instanceof BABYLON.Quaternion) {
  50412. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50413. }
  50414. else if (from instanceof BABYLON.Vector3) {
  50415. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50416. }
  50417. else if (from instanceof BABYLON.Vector2) {
  50418. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50419. }
  50420. else if (from instanceof BABYLON.Color3) {
  50421. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50422. }
  50423. else if (from instanceof BABYLON.Size) {
  50424. dataType = Animation.ANIMATIONTYPE_SIZE;
  50425. }
  50426. if (dataType == undefined) {
  50427. return null;
  50428. }
  50429. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50430. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50431. animation.setKeys(keys);
  50432. if (easingFunction !== undefined) {
  50433. animation.setEasingFunction(easingFunction);
  50434. }
  50435. return animation;
  50436. };
  50437. /**
  50438. * Sets up an animation
  50439. * @param property The property to animate
  50440. * @param animationType The animation type to apply
  50441. * @param framePerSecond The frames per second of the animation
  50442. * @param easingFunction The easing function used in the animation
  50443. * @returns The created animation
  50444. */
  50445. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50446. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50447. animation.setEasingFunction(easingFunction);
  50448. return animation;
  50449. };
  50450. /**
  50451. * Create and start an animation on a node
  50452. * @param name defines the name of the global animation that will be run on all nodes
  50453. * @param node defines the root node where the animation will take place
  50454. * @param targetProperty defines property to animate
  50455. * @param framePerSecond defines the number of frame per second yo use
  50456. * @param totalFrame defines the number of frames in total
  50457. * @param from defines the initial value
  50458. * @param to defines the final value
  50459. * @param loopMode defines which loop mode you want to use (off by default)
  50460. * @param easingFunction defines the easing function to use (linear by default)
  50461. * @param onAnimationEnd defines the callback to call when animation end
  50462. * @returns the animatable created for this animation
  50463. */
  50464. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50465. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50466. if (!animation) {
  50467. return null;
  50468. }
  50469. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50470. };
  50471. /**
  50472. * Create and start an animation on a node and its descendants
  50473. * @param name defines the name of the global animation that will be run on all nodes
  50474. * @param node defines the root node where the animation will take place
  50475. * @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
  50476. * @param targetProperty defines property to animate
  50477. * @param framePerSecond defines the number of frame per second to use
  50478. * @param totalFrame defines the number of frames in total
  50479. * @param from defines the initial value
  50480. * @param to defines the final value
  50481. * @param loopMode defines which loop mode you want to use (off by default)
  50482. * @param easingFunction defines the easing function to use (linear by default)
  50483. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50484. * @returns the list of animatables created for all nodes
  50485. * @example https://www.babylonjs-playground.com/#MH0VLI
  50486. */
  50487. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50488. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50489. if (!animation) {
  50490. return null;
  50491. }
  50492. var scene = node.getScene();
  50493. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50494. };
  50495. /**
  50496. * Creates a new animation, merges it with the existing animations and starts it
  50497. * @param name Name of the animation
  50498. * @param node Node which contains the scene that begins the animations
  50499. * @param targetProperty Specifies which property to animate
  50500. * @param framePerSecond The frames per second of the animation
  50501. * @param totalFrame The total number of frames
  50502. * @param from The frame at the beginning of the animation
  50503. * @param to The frame at the end of the animation
  50504. * @param loopMode Specifies the loop mode of the animation
  50505. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50506. * @param onAnimationEnd Callback to run once the animation is complete
  50507. * @returns Nullable animation
  50508. */
  50509. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50510. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50511. if (!animation) {
  50512. return null;
  50513. }
  50514. node.animations.push(animation);
  50515. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50516. };
  50517. /**
  50518. * Transition property of the Camera to the target Value
  50519. * @param property The property to transition
  50520. * @param targetValue The target Value of the property
  50521. * @param host The object where the property to animate belongs
  50522. * @param scene Scene used to run the animation
  50523. * @param frameRate Framerate (in frame/s) to use
  50524. * @param transition The transition type we want to use
  50525. * @param duration The duration of the animation, in milliseconds
  50526. * @param onAnimationEnd Callback trigger at the end of the animation
  50527. * @returns Nullable animation
  50528. */
  50529. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50530. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50531. if (duration <= 0) {
  50532. host[property] = targetValue;
  50533. if (onAnimationEnd) {
  50534. onAnimationEnd();
  50535. }
  50536. return null;
  50537. }
  50538. var endFrame = frameRate * (duration / 1000);
  50539. transition.setKeys([{
  50540. frame: 0,
  50541. value: host[property].clone ? host[property].clone() : host[property]
  50542. },
  50543. {
  50544. frame: endFrame,
  50545. value: targetValue
  50546. }]);
  50547. if (!host.animations) {
  50548. host.animations = [];
  50549. }
  50550. host.animations.push(transition);
  50551. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50552. animation.onAnimationEnd = onAnimationEnd;
  50553. return animation;
  50554. };
  50555. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50556. /**
  50557. * Return the array of runtime animations currently using this animation
  50558. */
  50559. get: function () {
  50560. return this._runtimeAnimations;
  50561. },
  50562. enumerable: true,
  50563. configurable: true
  50564. });
  50565. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50566. /**
  50567. * Specifies if any of the runtime animations are currently running
  50568. */
  50569. get: function () {
  50570. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50571. var runtimeAnimation = _a[_i];
  50572. if (!runtimeAnimation.isStopped) {
  50573. return true;
  50574. }
  50575. }
  50576. return false;
  50577. },
  50578. enumerable: true,
  50579. configurable: true
  50580. });
  50581. // Methods
  50582. /**
  50583. * Converts the animation to a string
  50584. * @param fullDetails support for multiple levels of logging within scene loading
  50585. * @returns String form of the animation
  50586. */
  50587. Animation.prototype.toString = function (fullDetails) {
  50588. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50589. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50590. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50591. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50592. if (fullDetails) {
  50593. ret += ", Ranges: {";
  50594. var first = true;
  50595. for (var name in this._ranges) {
  50596. if (first) {
  50597. ret += ", ";
  50598. first = false;
  50599. }
  50600. ret += name;
  50601. }
  50602. ret += "}";
  50603. }
  50604. return ret;
  50605. };
  50606. /**
  50607. * Add an event to this animation
  50608. * @param event Event to add
  50609. */
  50610. Animation.prototype.addEvent = function (event) {
  50611. this._events.push(event);
  50612. };
  50613. /**
  50614. * Remove all events found at the given frame
  50615. * @param frame The frame to remove events from
  50616. */
  50617. Animation.prototype.removeEvents = function (frame) {
  50618. for (var index = 0; index < this._events.length; index++) {
  50619. if (this._events[index].frame === frame) {
  50620. this._events.splice(index, 1);
  50621. index--;
  50622. }
  50623. }
  50624. };
  50625. /**
  50626. * Retrieves all the events from the animation
  50627. * @returns Events from the animation
  50628. */
  50629. Animation.prototype.getEvents = function () {
  50630. return this._events;
  50631. };
  50632. /**
  50633. * Creates an animation range
  50634. * @param name Name of the animation range
  50635. * @param from Starting frame of the animation range
  50636. * @param to Ending frame of the animation
  50637. */
  50638. Animation.prototype.createRange = function (name, from, to) {
  50639. // check name not already in use; could happen for bones after serialized
  50640. if (!this._ranges[name]) {
  50641. this._ranges[name] = new AnimationRange(name, from, to);
  50642. }
  50643. };
  50644. /**
  50645. * Deletes an animation range by name
  50646. * @param name Name of the animation range to delete
  50647. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50648. */
  50649. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50650. if (deleteFrames === void 0) { deleteFrames = true; }
  50651. var range = this._ranges[name];
  50652. if (!range) {
  50653. return;
  50654. }
  50655. if (deleteFrames) {
  50656. var from = range.from;
  50657. var to = range.to;
  50658. // this loop MUST go high to low for multiple splices to work
  50659. for (var key = this._keys.length - 1; key >= 0; key--) {
  50660. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50661. this._keys.splice(key, 1);
  50662. }
  50663. }
  50664. }
  50665. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50666. };
  50667. /**
  50668. * Gets the animation range by name, or null if not defined
  50669. * @param name Name of the animation range
  50670. * @returns Nullable animation range
  50671. */
  50672. Animation.prototype.getRange = function (name) {
  50673. return this._ranges[name];
  50674. };
  50675. /**
  50676. * Gets the key frames from the animation
  50677. * @returns The key frames of the animation
  50678. */
  50679. Animation.prototype.getKeys = function () {
  50680. return this._keys;
  50681. };
  50682. /**
  50683. * Gets the highest frame rate of the animation
  50684. * @returns Highest frame rate of the animation
  50685. */
  50686. Animation.prototype.getHighestFrame = function () {
  50687. var ret = 0;
  50688. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50689. if (ret < this._keys[key].frame) {
  50690. ret = this._keys[key].frame;
  50691. }
  50692. }
  50693. return ret;
  50694. };
  50695. /**
  50696. * Gets the easing function of the animation
  50697. * @returns Easing function of the animation
  50698. */
  50699. Animation.prototype.getEasingFunction = function () {
  50700. return this._easingFunction;
  50701. };
  50702. /**
  50703. * Sets the easing function of the animation
  50704. * @param easingFunction A custom mathematical formula for animation
  50705. */
  50706. Animation.prototype.setEasingFunction = function (easingFunction) {
  50707. this._easingFunction = easingFunction;
  50708. };
  50709. /**
  50710. * Interpolates a scalar linearly
  50711. * @param startValue Start value of the animation curve
  50712. * @param endValue End value of the animation curve
  50713. * @param gradient Scalar amount to interpolate
  50714. * @returns Interpolated scalar value
  50715. */
  50716. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50717. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50718. };
  50719. /**
  50720. * Interpolates a scalar cubically
  50721. * @param startValue Start value of the animation curve
  50722. * @param outTangent End tangent of the animation
  50723. * @param endValue End value of the animation curve
  50724. * @param inTangent Start tangent of the animation curve
  50725. * @param gradient Scalar amount to interpolate
  50726. * @returns Interpolated scalar value
  50727. */
  50728. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50729. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50730. };
  50731. /**
  50732. * Interpolates a quaternion using a spherical linear interpolation
  50733. * @param startValue Start value of the animation curve
  50734. * @param endValue End value of the animation curve
  50735. * @param gradient Scalar amount to interpolate
  50736. * @returns Interpolated quaternion value
  50737. */
  50738. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50739. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50740. };
  50741. /**
  50742. * Interpolates a quaternion cubically
  50743. * @param startValue Start value of the animation curve
  50744. * @param outTangent End tangent of the animation curve
  50745. * @param endValue End value of the animation curve
  50746. * @param inTangent Start tangent of the animation curve
  50747. * @param gradient Scalar amount to interpolate
  50748. * @returns Interpolated quaternion value
  50749. */
  50750. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50751. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50752. };
  50753. /**
  50754. * Interpolates a Vector3 linearl
  50755. * @param startValue Start value of the animation curve
  50756. * @param endValue End value of the animation curve
  50757. * @param gradient Scalar amount to interpolate
  50758. * @returns Interpolated scalar value
  50759. */
  50760. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50761. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50762. };
  50763. /**
  50764. * Interpolates a Vector3 cubically
  50765. * @param startValue Start value of the animation curve
  50766. * @param outTangent End tangent of the animation
  50767. * @param endValue End value of the animation curve
  50768. * @param inTangent Start tangent of the animation curve
  50769. * @param gradient Scalar amount to interpolate
  50770. * @returns InterpolatedVector3 value
  50771. */
  50772. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50773. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50774. };
  50775. /**
  50776. * Interpolates a Vector2 linearly
  50777. * @param startValue Start value of the animation curve
  50778. * @param endValue End value of the animation curve
  50779. * @param gradient Scalar amount to interpolate
  50780. * @returns Interpolated Vector2 value
  50781. */
  50782. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50783. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50784. };
  50785. /**
  50786. * Interpolates a Vector2 cubically
  50787. * @param startValue Start value of the animation curve
  50788. * @param outTangent End tangent of the animation
  50789. * @param endValue End value of the animation curve
  50790. * @param inTangent Start tangent of the animation curve
  50791. * @param gradient Scalar amount to interpolate
  50792. * @returns Interpolated Vector2 value
  50793. */
  50794. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50795. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50796. };
  50797. /**
  50798. * Interpolates a size linearly
  50799. * @param startValue Start value of the animation curve
  50800. * @param endValue End value of the animation curve
  50801. * @param gradient Scalar amount to interpolate
  50802. * @returns Interpolated Size value
  50803. */
  50804. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50805. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50806. };
  50807. /**
  50808. * Interpolates a Color3 linearly
  50809. * @param startValue Start value of the animation curve
  50810. * @param endValue End value of the animation curve
  50811. * @param gradient Scalar amount to interpolate
  50812. * @returns Interpolated Color3 value
  50813. */
  50814. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50815. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50816. };
  50817. /**
  50818. * @hidden Internal use only
  50819. */
  50820. Animation.prototype._getKeyValue = function (value) {
  50821. if (typeof value === "function") {
  50822. return value();
  50823. }
  50824. return value;
  50825. };
  50826. /**
  50827. * @hidden Internal use only
  50828. */
  50829. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50830. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50831. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50832. }
  50833. var keys = this.getKeys();
  50834. // Try to get a hash to find the right key
  50835. 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));
  50836. if (keys[startKeyIndex].frame >= currentFrame) {
  50837. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50838. startKeyIndex--;
  50839. }
  50840. }
  50841. for (var key = startKeyIndex; key < keys.length; key++) {
  50842. var endKey = keys[key + 1];
  50843. if (endKey.frame >= currentFrame) {
  50844. var startKey = keys[key];
  50845. var startValue = this._getKeyValue(startKey.value);
  50846. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50847. return startValue;
  50848. }
  50849. var endValue = this._getKeyValue(endKey.value);
  50850. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50851. var frameDelta = endKey.frame - startKey.frame;
  50852. // gradient : percent of currentFrame between the frame inf and the frame sup
  50853. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50854. // check for easingFunction and correction of gradient
  50855. var easingFunction = this.getEasingFunction();
  50856. if (easingFunction != null) {
  50857. gradient = easingFunction.ease(gradient);
  50858. }
  50859. switch (this.dataType) {
  50860. // Float
  50861. case Animation.ANIMATIONTYPE_FLOAT:
  50862. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50863. switch (loopMode) {
  50864. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50865. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50866. return floatValue;
  50867. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50868. return offsetValue * repeatCount + floatValue;
  50869. }
  50870. break;
  50871. // Quaternion
  50872. case Animation.ANIMATIONTYPE_QUATERNION:
  50873. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50874. switch (loopMode) {
  50875. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50876. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50877. return quatValue;
  50878. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50879. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50880. }
  50881. return quatValue;
  50882. // Vector3
  50883. case Animation.ANIMATIONTYPE_VECTOR3:
  50884. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50885. switch (loopMode) {
  50886. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50887. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50888. return vec3Value;
  50889. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50890. return vec3Value.add(offsetValue.scale(repeatCount));
  50891. }
  50892. // Vector2
  50893. case Animation.ANIMATIONTYPE_VECTOR2:
  50894. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50895. switch (loopMode) {
  50896. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50897. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50898. return vec2Value;
  50899. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50900. return vec2Value.add(offsetValue.scale(repeatCount));
  50901. }
  50902. // Size
  50903. case Animation.ANIMATIONTYPE_SIZE:
  50904. switch (loopMode) {
  50905. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50906. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50907. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50908. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50909. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50910. }
  50911. // Color3
  50912. case Animation.ANIMATIONTYPE_COLOR3:
  50913. switch (loopMode) {
  50914. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50915. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50916. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50917. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50918. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50919. }
  50920. // Matrix
  50921. case Animation.ANIMATIONTYPE_MATRIX:
  50922. switch (loopMode) {
  50923. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50924. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50925. if (Animation.AllowMatricesInterpolation) {
  50926. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50927. }
  50928. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50929. return startValue;
  50930. }
  50931. default:
  50932. break;
  50933. }
  50934. break;
  50935. }
  50936. }
  50937. return this._getKeyValue(keys[keys.length - 1].value);
  50938. };
  50939. /**
  50940. * Defines the function to use to interpolate matrices
  50941. * @param startValue defines the start matrix
  50942. * @param endValue defines the end matrix
  50943. * @param gradient defines the gradient between both matrices
  50944. * @param result defines an optional target matrix where to store the interpolation
  50945. * @returns the interpolated matrix
  50946. */
  50947. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50948. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50949. if (result) {
  50950. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50951. return result;
  50952. }
  50953. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50954. }
  50955. if (result) {
  50956. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50957. return result;
  50958. }
  50959. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50960. };
  50961. /**
  50962. * Makes a copy of the animation
  50963. * @returns Cloned animation
  50964. */
  50965. Animation.prototype.clone = function () {
  50966. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50967. clone.enableBlending = this.enableBlending;
  50968. clone.blendingSpeed = this.blendingSpeed;
  50969. if (this._keys) {
  50970. clone.setKeys(this._keys);
  50971. }
  50972. if (this._ranges) {
  50973. clone._ranges = {};
  50974. for (var name in this._ranges) {
  50975. var range = this._ranges[name];
  50976. if (!range) {
  50977. continue;
  50978. }
  50979. clone._ranges[name] = range.clone();
  50980. }
  50981. }
  50982. return clone;
  50983. };
  50984. /**
  50985. * Sets the key frames of the animation
  50986. * @param values The animation key frames to set
  50987. */
  50988. Animation.prototype.setKeys = function (values) {
  50989. this._keys = values.slice(0);
  50990. };
  50991. /**
  50992. * Serializes the animation to an object
  50993. * @returns Serialized object
  50994. */
  50995. Animation.prototype.serialize = function () {
  50996. var serializationObject = {};
  50997. serializationObject.name = this.name;
  50998. serializationObject.property = this.targetProperty;
  50999. serializationObject.framePerSecond = this.framePerSecond;
  51000. serializationObject.dataType = this.dataType;
  51001. serializationObject.loopBehavior = this.loopMode;
  51002. serializationObject.enableBlending = this.enableBlending;
  51003. serializationObject.blendingSpeed = this.blendingSpeed;
  51004. var dataType = this.dataType;
  51005. serializationObject.keys = [];
  51006. var keys = this.getKeys();
  51007. for (var index = 0; index < keys.length; index++) {
  51008. var animationKey = keys[index];
  51009. var key = {};
  51010. key.frame = animationKey.frame;
  51011. switch (dataType) {
  51012. case Animation.ANIMATIONTYPE_FLOAT:
  51013. key.values = [animationKey.value];
  51014. break;
  51015. case Animation.ANIMATIONTYPE_QUATERNION:
  51016. case Animation.ANIMATIONTYPE_MATRIX:
  51017. case Animation.ANIMATIONTYPE_VECTOR3:
  51018. case Animation.ANIMATIONTYPE_COLOR3:
  51019. key.values = animationKey.value.asArray();
  51020. break;
  51021. }
  51022. serializationObject.keys.push(key);
  51023. }
  51024. serializationObject.ranges = [];
  51025. for (var name in this._ranges) {
  51026. var source = this._ranges[name];
  51027. if (!source) {
  51028. continue;
  51029. }
  51030. var range = {};
  51031. range.name = name;
  51032. range.from = source.from;
  51033. range.to = source.to;
  51034. serializationObject.ranges.push(range);
  51035. }
  51036. return serializationObject;
  51037. };
  51038. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51039. /**
  51040. * Get the float animation type
  51041. */
  51042. get: function () {
  51043. return Animation._ANIMATIONTYPE_FLOAT;
  51044. },
  51045. enumerable: true,
  51046. configurable: true
  51047. });
  51048. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51049. /**
  51050. * Get the Vector3 animation type
  51051. */
  51052. get: function () {
  51053. return Animation._ANIMATIONTYPE_VECTOR3;
  51054. },
  51055. enumerable: true,
  51056. configurable: true
  51057. });
  51058. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51059. /**
  51060. * Get the Vectpr2 animation type
  51061. */
  51062. get: function () {
  51063. return Animation._ANIMATIONTYPE_VECTOR2;
  51064. },
  51065. enumerable: true,
  51066. configurable: true
  51067. });
  51068. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51069. /**
  51070. * Get the Size animation type
  51071. */
  51072. get: function () {
  51073. return Animation._ANIMATIONTYPE_SIZE;
  51074. },
  51075. enumerable: true,
  51076. configurable: true
  51077. });
  51078. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51079. /**
  51080. * Get the Quaternion animation type
  51081. */
  51082. get: function () {
  51083. return Animation._ANIMATIONTYPE_QUATERNION;
  51084. },
  51085. enumerable: true,
  51086. configurable: true
  51087. });
  51088. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51089. /**
  51090. * Get the Matrix animation type
  51091. */
  51092. get: function () {
  51093. return Animation._ANIMATIONTYPE_MATRIX;
  51094. },
  51095. enumerable: true,
  51096. configurable: true
  51097. });
  51098. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51099. /**
  51100. * Get the Color3 animation type
  51101. */
  51102. get: function () {
  51103. return Animation._ANIMATIONTYPE_COLOR3;
  51104. },
  51105. enumerable: true,
  51106. configurable: true
  51107. });
  51108. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51109. /**
  51110. * Get the Relative Loop Mode
  51111. */
  51112. get: function () {
  51113. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51114. },
  51115. enumerable: true,
  51116. configurable: true
  51117. });
  51118. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51119. /**
  51120. * Get the Cycle Loop Mode
  51121. */
  51122. get: function () {
  51123. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51124. },
  51125. enumerable: true,
  51126. configurable: true
  51127. });
  51128. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51129. /**
  51130. * Get the Constant Loop Mode
  51131. */
  51132. get: function () {
  51133. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51134. },
  51135. enumerable: true,
  51136. configurable: true
  51137. });
  51138. /** @hidden */
  51139. Animation._UniversalLerp = function (left, right, amount) {
  51140. var constructor = left.constructor;
  51141. if (constructor.Lerp) { // Lerp supported
  51142. return constructor.Lerp(left, right, amount);
  51143. }
  51144. else if (constructor.Slerp) { // Slerp supported
  51145. return constructor.Slerp(left, right, amount);
  51146. }
  51147. else if (left.toFixed) { // Number
  51148. return left * (1.0 - amount) + amount * right;
  51149. }
  51150. else { // Blending not supported
  51151. return right;
  51152. }
  51153. };
  51154. /**
  51155. * Parses an animation object and creates an animation
  51156. * @param parsedAnimation Parsed animation object
  51157. * @returns Animation object
  51158. */
  51159. Animation.Parse = function (parsedAnimation) {
  51160. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51161. var dataType = parsedAnimation.dataType;
  51162. var keys = [];
  51163. var data;
  51164. var index;
  51165. if (parsedAnimation.enableBlending) {
  51166. animation.enableBlending = parsedAnimation.enableBlending;
  51167. }
  51168. if (parsedAnimation.blendingSpeed) {
  51169. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51170. }
  51171. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51172. var key = parsedAnimation.keys[index];
  51173. var inTangent;
  51174. var outTangent;
  51175. switch (dataType) {
  51176. case Animation.ANIMATIONTYPE_FLOAT:
  51177. data = key.values[0];
  51178. if (key.values.length >= 1) {
  51179. inTangent = key.values[1];
  51180. }
  51181. if (key.values.length >= 2) {
  51182. outTangent = key.values[2];
  51183. }
  51184. break;
  51185. case Animation.ANIMATIONTYPE_QUATERNION:
  51186. data = BABYLON.Quaternion.FromArray(key.values);
  51187. if (key.values.length >= 8) {
  51188. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51189. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51190. inTangent = _inTangent;
  51191. }
  51192. }
  51193. if (key.values.length >= 12) {
  51194. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51195. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51196. outTangent = _outTangent;
  51197. }
  51198. }
  51199. break;
  51200. case Animation.ANIMATIONTYPE_MATRIX:
  51201. data = BABYLON.Matrix.FromArray(key.values);
  51202. break;
  51203. case Animation.ANIMATIONTYPE_COLOR3:
  51204. data = BABYLON.Color3.FromArray(key.values);
  51205. break;
  51206. case Animation.ANIMATIONTYPE_VECTOR3:
  51207. default:
  51208. data = BABYLON.Vector3.FromArray(key.values);
  51209. break;
  51210. }
  51211. var keyData = {};
  51212. keyData.frame = key.frame;
  51213. keyData.value = data;
  51214. if (inTangent != undefined) {
  51215. keyData.inTangent = inTangent;
  51216. }
  51217. if (outTangent != undefined) {
  51218. keyData.outTangent = outTangent;
  51219. }
  51220. keys.push(keyData);
  51221. }
  51222. animation.setKeys(keys);
  51223. if (parsedAnimation.ranges) {
  51224. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51225. data = parsedAnimation.ranges[index];
  51226. animation.createRange(data.name, data.from, data.to);
  51227. }
  51228. }
  51229. return animation;
  51230. };
  51231. /**
  51232. * Appends the serialized animations from the source animations
  51233. * @param source Source containing the animations
  51234. * @param destination Target to store the animations
  51235. */
  51236. Animation.AppendSerializedAnimations = function (source, destination) {
  51237. if (source.animations) {
  51238. destination.animations = [];
  51239. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51240. var animation = source.animations[animationIndex];
  51241. destination.animations.push(animation.serialize());
  51242. }
  51243. }
  51244. };
  51245. /**
  51246. * Use matrix interpolation instead of using direct key value when animating matrices
  51247. */
  51248. Animation.AllowMatricesInterpolation = false;
  51249. /**
  51250. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51251. */
  51252. Animation.AllowMatrixDecomposeForInterpolation = true;
  51253. // Statics
  51254. /**
  51255. * Float animation type
  51256. */
  51257. Animation._ANIMATIONTYPE_FLOAT = 0;
  51258. /**
  51259. * Vector3 animation type
  51260. */
  51261. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51262. /**
  51263. * Quaternion animation type
  51264. */
  51265. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51266. /**
  51267. * Matrix animation type
  51268. */
  51269. Animation._ANIMATIONTYPE_MATRIX = 3;
  51270. /**
  51271. * Color3 animation type
  51272. */
  51273. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51274. /**
  51275. * Vector2 animation type
  51276. */
  51277. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51278. /**
  51279. * Size animation type
  51280. */
  51281. Animation._ANIMATIONTYPE_SIZE = 6;
  51282. /**
  51283. * Relative Loop Mode
  51284. */
  51285. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51286. /**
  51287. * Cycle Loop Mode
  51288. */
  51289. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51290. /**
  51291. * Constant Loop Mode
  51292. */
  51293. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51294. return Animation;
  51295. }());
  51296. BABYLON.Animation = Animation;
  51297. })(BABYLON || (BABYLON = {}));
  51298. //# sourceMappingURL=babylon.animation.js.map
  51299. var BABYLON;
  51300. (function (BABYLON) {
  51301. /**
  51302. * This class defines the direct association between an animation and a target
  51303. */
  51304. var TargetedAnimation = /** @class */ (function () {
  51305. function TargetedAnimation() {
  51306. }
  51307. return TargetedAnimation;
  51308. }());
  51309. BABYLON.TargetedAnimation = TargetedAnimation;
  51310. /**
  51311. * Use this class to create coordinated animations on multiple targets
  51312. */
  51313. var AnimationGroup = /** @class */ (function () {
  51314. function AnimationGroup(name, scene) {
  51315. if (scene === void 0) { scene = null; }
  51316. this.name = name;
  51317. this._targetedAnimations = new Array();
  51318. this._animatables = new Array();
  51319. this._from = Number.MAX_VALUE;
  51320. this._to = -Number.MAX_VALUE;
  51321. this._speedRatio = 1;
  51322. this.onAnimationEndObservable = new BABYLON.Observable();
  51323. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51324. this._scene.animationGroups.push(this);
  51325. }
  51326. Object.defineProperty(AnimationGroup.prototype, "from", {
  51327. /**
  51328. * Gets the first frame
  51329. */
  51330. get: function () {
  51331. return this._from;
  51332. },
  51333. enumerable: true,
  51334. configurable: true
  51335. });
  51336. Object.defineProperty(AnimationGroup.prototype, "to", {
  51337. /**
  51338. * Gets the last frame
  51339. */
  51340. get: function () {
  51341. return this._to;
  51342. },
  51343. enumerable: true,
  51344. configurable: true
  51345. });
  51346. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51347. /**
  51348. * Define if the animations are started
  51349. */
  51350. get: function () {
  51351. return this._isStarted;
  51352. },
  51353. enumerable: true,
  51354. configurable: true
  51355. });
  51356. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51357. /**
  51358. * Gets or sets the speed ratio to use for all animations
  51359. */
  51360. get: function () {
  51361. return this._speedRatio;
  51362. },
  51363. /**
  51364. * Gets or sets the speed ratio to use for all animations
  51365. */
  51366. set: function (value) {
  51367. if (this._speedRatio === value) {
  51368. return;
  51369. }
  51370. this._speedRatio = value;
  51371. for (var index = 0; index < this._animatables.length; index++) {
  51372. var animatable = this._animatables[index];
  51373. animatable.speedRatio = this._speedRatio;
  51374. }
  51375. },
  51376. enumerable: true,
  51377. configurable: true
  51378. });
  51379. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51380. /**
  51381. * Gets the targeted animations for this animation group
  51382. */
  51383. get: function () {
  51384. return this._targetedAnimations;
  51385. },
  51386. enumerable: true,
  51387. configurable: true
  51388. });
  51389. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51390. /**
  51391. * returning the list of animatables controlled by this animation group.
  51392. */
  51393. get: function () {
  51394. return this._animatables;
  51395. },
  51396. enumerable: true,
  51397. configurable: true
  51398. });
  51399. /**
  51400. * Add an animation (with its target) in the group
  51401. * @param animation defines the animation we want to add
  51402. * @param target defines the target of the animation
  51403. * @returns the {BABYLON.TargetedAnimation} object
  51404. */
  51405. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51406. var targetedAnimation = {
  51407. animation: animation,
  51408. target: target
  51409. };
  51410. var keys = animation.getKeys();
  51411. if (this._from > keys[0].frame) {
  51412. this._from = keys[0].frame;
  51413. }
  51414. if (this._to < keys[keys.length - 1].frame) {
  51415. this._to = keys[keys.length - 1].frame;
  51416. }
  51417. this._targetedAnimations.push(targetedAnimation);
  51418. return targetedAnimation;
  51419. };
  51420. /**
  51421. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51422. * It can add constant keys at begin or end
  51423. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51424. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51425. */
  51426. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51427. if (beginFrame === void 0) { beginFrame = null; }
  51428. if (endFrame === void 0) { endFrame = null; }
  51429. if (beginFrame == null)
  51430. beginFrame = this._from;
  51431. if (endFrame == null)
  51432. endFrame = this._to;
  51433. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51434. var targetedAnimation = this._targetedAnimations[index];
  51435. var keys = targetedAnimation.animation.getKeys();
  51436. var startKey = keys[0];
  51437. var endKey = keys[keys.length - 1];
  51438. if (startKey.frame > beginFrame) {
  51439. var newKey = {
  51440. frame: beginFrame,
  51441. value: startKey.value,
  51442. inTangent: startKey.inTangent,
  51443. outTangent: startKey.outTangent,
  51444. interpolation: startKey.interpolation
  51445. };
  51446. keys.splice(0, 0, newKey);
  51447. }
  51448. if (endKey.frame < endFrame) {
  51449. var newKey = {
  51450. frame: endFrame,
  51451. value: endKey.value,
  51452. inTangent: endKey.outTangent,
  51453. outTangent: endKey.outTangent,
  51454. interpolation: endKey.interpolation
  51455. };
  51456. keys.push(newKey);
  51457. }
  51458. }
  51459. this._from = beginFrame;
  51460. this._to = endFrame;
  51461. return this;
  51462. };
  51463. /**
  51464. * Start all animations on given targets
  51465. * @param loop defines if animations must loop
  51466. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51467. * @param from defines the from key (optional)
  51468. * @param to defines the to key (optional)
  51469. * @returns the current animation group
  51470. */
  51471. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51472. var _this = this;
  51473. if (loop === void 0) { loop = false; }
  51474. if (speedRatio === void 0) { speedRatio = 1; }
  51475. if (this._isStarted || this._targetedAnimations.length === 0) {
  51476. return this;
  51477. }
  51478. var _loop_1 = function (targetedAnimation) {
  51479. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  51480. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51481. }));
  51482. };
  51483. var this_1 = this;
  51484. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51485. var targetedAnimation = _a[_i];
  51486. _loop_1(targetedAnimation);
  51487. }
  51488. this._speedRatio = speedRatio;
  51489. this._isStarted = true;
  51490. return this;
  51491. };
  51492. /**
  51493. * Pause all animations
  51494. */
  51495. AnimationGroup.prototype.pause = function () {
  51496. if (!this._isStarted) {
  51497. return this;
  51498. }
  51499. for (var index = 0; index < this._animatables.length; index++) {
  51500. var animatable = this._animatables[index];
  51501. animatable.pause();
  51502. }
  51503. return this;
  51504. };
  51505. /**
  51506. * Play all animations to initial state
  51507. * This function will start() the animations if they were not started or will restart() them if they were paused
  51508. * @param loop defines if animations must loop
  51509. */
  51510. AnimationGroup.prototype.play = function (loop) {
  51511. if (this.isStarted) {
  51512. if (loop !== undefined) {
  51513. for (var index = 0; index < this._animatables.length; index++) {
  51514. var animatable = this._animatables[index];
  51515. animatable.loopAnimation = loop;
  51516. }
  51517. }
  51518. this.restart();
  51519. }
  51520. else {
  51521. this.start(loop, this._speedRatio);
  51522. }
  51523. return this;
  51524. };
  51525. /**
  51526. * Reset all animations to initial state
  51527. */
  51528. AnimationGroup.prototype.reset = function () {
  51529. if (!this._isStarted) {
  51530. return this;
  51531. }
  51532. for (var index = 0; index < this._animatables.length; index++) {
  51533. var animatable = this._animatables[index];
  51534. animatable.reset();
  51535. }
  51536. return this;
  51537. };
  51538. /**
  51539. * Restart animations from key 0
  51540. */
  51541. AnimationGroup.prototype.restart = function () {
  51542. if (!this._isStarted) {
  51543. return this;
  51544. }
  51545. for (var index = 0; index < this._animatables.length; index++) {
  51546. var animatable = this._animatables[index];
  51547. animatable.restart();
  51548. }
  51549. return this;
  51550. };
  51551. /**
  51552. * Stop all animations
  51553. */
  51554. AnimationGroup.prototype.stop = function () {
  51555. if (!this._isStarted) {
  51556. return this;
  51557. }
  51558. for (var index = 0; index < this._animatables.length; index++) {
  51559. var animatable = this._animatables[index];
  51560. animatable.stop();
  51561. }
  51562. this._isStarted = false;
  51563. return this;
  51564. };
  51565. /**
  51566. * Set animation weight for all animatables
  51567. * @param weight defines the weight to use
  51568. * @return the animationGroup
  51569. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51570. */
  51571. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51572. for (var index = 0; index < this._animatables.length; index++) {
  51573. var animatable = this._animatables[index];
  51574. animatable.weight = weight;
  51575. }
  51576. return this;
  51577. };
  51578. /**
  51579. * Synchronize and normalize all animatables with a source animatable
  51580. * @param root defines the root animatable to synchronize with
  51581. * @return the animationGroup
  51582. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51583. */
  51584. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51585. for (var index = 0; index < this._animatables.length; index++) {
  51586. var animatable = this._animatables[index];
  51587. animatable.syncWith(root);
  51588. }
  51589. return this;
  51590. };
  51591. /**
  51592. * Goes to a specific frame in this animation group
  51593. * @param frame the frame number to go to
  51594. * @return the animationGroup
  51595. */
  51596. AnimationGroup.prototype.goToFrame = function (frame) {
  51597. if (!this._isStarted) {
  51598. return this;
  51599. }
  51600. for (var index = 0; index < this._animatables.length; index++) {
  51601. var animatable = this._animatables[index];
  51602. animatable.goToFrame(frame);
  51603. }
  51604. return this;
  51605. };
  51606. /**
  51607. * Dispose all associated resources
  51608. */
  51609. AnimationGroup.prototype.dispose = function () {
  51610. this._targetedAnimations = [];
  51611. this._animatables = [];
  51612. var index = this._scene.animationGroups.indexOf(this);
  51613. if (index > -1) {
  51614. this._scene.animationGroups.splice(index, 1);
  51615. }
  51616. };
  51617. return AnimationGroup;
  51618. }());
  51619. BABYLON.AnimationGroup = AnimationGroup;
  51620. })(BABYLON || (BABYLON = {}));
  51621. //# sourceMappingURL=babylon.animationGroup.js.map
  51622. var BABYLON;
  51623. (function (BABYLON) {
  51624. /**
  51625. * Defines a runtime animation
  51626. */
  51627. var RuntimeAnimation = /** @class */ (function () {
  51628. /**
  51629. * Create a new RuntimeAnimation object
  51630. * @param target defines the target of the animation
  51631. * @param animation defines the source animation object
  51632. * @param scene defines the hosting scene
  51633. * @param host defines the initiating Animatable
  51634. */
  51635. function RuntimeAnimation(target, animation, scene, host) {
  51636. /**
  51637. * The current frame of the runtime animation
  51638. */
  51639. this._currentFrame = 0;
  51640. /**
  51641. * The original value of the runtime animation
  51642. */
  51643. this._originalValue = new Array();
  51644. /**
  51645. * The offsets cache of the runtime animation
  51646. */
  51647. this._offsetsCache = {};
  51648. /**
  51649. * The high limits cache of the runtime animation
  51650. */
  51651. this._highLimitsCache = {};
  51652. /**
  51653. * Specifies if the runtime animation has been stopped
  51654. */
  51655. this._stopped = false;
  51656. /**
  51657. * The blending factor of the runtime animation
  51658. */
  51659. this._blendingFactor = 0;
  51660. /**
  51661. * The target path of the runtime animation
  51662. */
  51663. this._targetPath = "";
  51664. /**
  51665. * The weight of the runtime animation
  51666. */
  51667. this._weight = 1.0;
  51668. /**
  51669. * The ratio offset of the runtime animation
  51670. */
  51671. this._ratioOffset = 0;
  51672. /**
  51673. * The previous delay of the runtime animation
  51674. */
  51675. this._previousDelay = 0;
  51676. /**
  51677. * The previous ratio of the runtime animation
  51678. */
  51679. this._previousRatio = 0;
  51680. this._animation = animation;
  51681. this._target = target;
  51682. this._scene = scene;
  51683. this._host = host;
  51684. animation._runtimeAnimations.push(this);
  51685. }
  51686. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51687. /**
  51688. * Gets the current frame of the runtime animation
  51689. */
  51690. get: function () {
  51691. return this._currentFrame;
  51692. },
  51693. enumerable: true,
  51694. configurable: true
  51695. });
  51696. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51697. /**
  51698. * Gets the weight of the runtime animation
  51699. */
  51700. get: function () {
  51701. return this._weight;
  51702. },
  51703. enumerable: true,
  51704. configurable: true
  51705. });
  51706. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51707. /**
  51708. * Gets the current value of the runtime animation
  51709. */
  51710. get: function () {
  51711. return this._currentValue;
  51712. },
  51713. enumerable: true,
  51714. configurable: true
  51715. });
  51716. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51717. /**
  51718. * Gets the target path of the runtime animation
  51719. */
  51720. get: function () {
  51721. return this._targetPath;
  51722. },
  51723. enumerable: true,
  51724. configurable: true
  51725. });
  51726. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51727. /**
  51728. * Gets the actual target of the runtime animation
  51729. */
  51730. get: function () {
  51731. return this._activeTarget;
  51732. },
  51733. enumerable: true,
  51734. configurable: true
  51735. });
  51736. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51737. /**
  51738. * Gets the animation from the runtime animation
  51739. */
  51740. get: function () {
  51741. return this._animation;
  51742. },
  51743. enumerable: true,
  51744. configurable: true
  51745. });
  51746. /**
  51747. * Resets the runtime animation to the beginning
  51748. * @param restoreOriginal defines whether to restore the target property to the original value
  51749. */
  51750. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51751. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51752. if (restoreOriginal) {
  51753. if (this._target instanceof Array) {
  51754. var index = 0;
  51755. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51756. var target = _a[_i];
  51757. if (this._originalValue[index] !== undefined) {
  51758. this._setValue(target, this._originalValue[index], -1);
  51759. }
  51760. index++;
  51761. }
  51762. }
  51763. else {
  51764. if (this._originalValue[0] !== undefined) {
  51765. this._setValue(this._target, this._originalValue[0], -1);
  51766. }
  51767. }
  51768. }
  51769. this._offsetsCache = {};
  51770. this._highLimitsCache = {};
  51771. this._currentFrame = 0;
  51772. this._blendingFactor = 0;
  51773. this._originalValue = new Array();
  51774. };
  51775. /**
  51776. * Specifies if the runtime animation is stopped
  51777. * @returns Boolean specifying if the runtime animation is stopped
  51778. */
  51779. RuntimeAnimation.prototype.isStopped = function () {
  51780. return this._stopped;
  51781. };
  51782. /**
  51783. * Disposes of the runtime animation
  51784. */
  51785. RuntimeAnimation.prototype.dispose = function () {
  51786. var index = this._animation.runtimeAnimations.indexOf(this);
  51787. if (index > -1) {
  51788. this._animation.runtimeAnimations.splice(index, 1);
  51789. }
  51790. };
  51791. /**
  51792. * Interpolates the animation from the current frame
  51793. * @param currentFrame The frame to interpolate the animation to
  51794. * @param repeatCount The number of times that the animation should loop
  51795. * @param loopMode The type of looping mode to use
  51796. * @param offsetValue Animation offset value
  51797. * @param highLimitValue The high limit value
  51798. * @returns The interpolated value
  51799. */
  51800. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51801. this._currentFrame = currentFrame;
  51802. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51803. this._workValue = BABYLON.Matrix.Zero();
  51804. }
  51805. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51806. };
  51807. /**
  51808. * Apply the interpolated value to the target
  51809. * @param currentValue defines the value computed by the animation
  51810. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51811. */
  51812. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51813. if (weight === void 0) { weight = 1.0; }
  51814. if (this._target instanceof Array) {
  51815. var index = 0;
  51816. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51817. var target = _a[_i];
  51818. this._setValue(target, currentValue, weight, index);
  51819. index++;
  51820. }
  51821. }
  51822. else {
  51823. this._setValue(this._target, currentValue, weight);
  51824. }
  51825. };
  51826. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51827. if (targetIndex === void 0) { targetIndex = 0; }
  51828. // Set value
  51829. var path;
  51830. var destination;
  51831. var targetPropertyPath = this._animation.targetPropertyPath;
  51832. if (targetPropertyPath.length > 1) {
  51833. var property = target[targetPropertyPath[0]];
  51834. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51835. property = property[targetPropertyPath[index]];
  51836. }
  51837. path = targetPropertyPath[targetPropertyPath.length - 1];
  51838. destination = property;
  51839. }
  51840. else {
  51841. path = targetPropertyPath[0];
  51842. destination = target;
  51843. }
  51844. this._targetPath = path;
  51845. this._activeTarget = destination;
  51846. this._weight = weight;
  51847. if (this._originalValue[targetIndex] === undefined) {
  51848. var originalValue = void 0;
  51849. if (destination.getRestPose && path === "_matrix") { // For bones
  51850. originalValue = destination.getRestPose();
  51851. }
  51852. else {
  51853. originalValue = destination[path];
  51854. }
  51855. if (originalValue && originalValue.clone) {
  51856. this._originalValue[targetIndex] = originalValue.clone();
  51857. }
  51858. else {
  51859. this._originalValue[targetIndex] = originalValue;
  51860. }
  51861. }
  51862. // Blending
  51863. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51864. if (enableBlending && this._blendingFactor <= 1.0) {
  51865. if (!this._originalBlendValue) {
  51866. var originalValue = destination[path];
  51867. if (originalValue.clone) {
  51868. this._originalBlendValue = originalValue.clone();
  51869. }
  51870. else {
  51871. this._originalBlendValue = originalValue;
  51872. }
  51873. }
  51874. if (this._originalBlendValue.m) { // Matrix
  51875. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51876. if (this._currentValue) {
  51877. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51878. }
  51879. else {
  51880. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51881. }
  51882. }
  51883. else {
  51884. if (this._currentValue) {
  51885. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51886. }
  51887. else {
  51888. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51889. }
  51890. }
  51891. }
  51892. else {
  51893. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51894. }
  51895. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51896. this._blendingFactor += blendingSpeed;
  51897. }
  51898. else {
  51899. this._currentValue = currentValue;
  51900. }
  51901. if (weight !== -1.0) {
  51902. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51903. }
  51904. else {
  51905. destination[path] = this._currentValue;
  51906. }
  51907. if (target.markAsDirty) {
  51908. target.markAsDirty(this._animation.targetProperty);
  51909. }
  51910. };
  51911. /**
  51912. * Gets the loop pmode of the runtime animation
  51913. * @returns Loop Mode
  51914. */
  51915. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51916. if (this._target && this._target.animationPropertiesOverride) {
  51917. return this._target.animationPropertiesOverride.loopMode;
  51918. }
  51919. return this._animation.loopMode;
  51920. };
  51921. /**
  51922. * Move the current animation to a given frame
  51923. * @param frame defines the frame to move to
  51924. */
  51925. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51926. var keys = this._animation.getKeys();
  51927. if (frame < keys[0].frame) {
  51928. frame = keys[0].frame;
  51929. }
  51930. else if (frame > keys[keys.length - 1].frame) {
  51931. frame = keys[keys.length - 1].frame;
  51932. }
  51933. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51934. this.setValue(currentValue, -1);
  51935. };
  51936. /**
  51937. * @hidden Internal use only
  51938. */
  51939. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51940. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51941. this._ratioOffset = this._previousRatio - newRatio;
  51942. };
  51943. /**
  51944. * Execute the current animation
  51945. * @param delay defines the delay to add to the current frame
  51946. * @param from defines the lower bound of the animation range
  51947. * @param to defines the upper bound of the animation range
  51948. * @param loop defines if the current animation must loop
  51949. * @param speedRatio defines the current speed ratio
  51950. * @param weight defines the weight of the animation (default is -1 so no weight)
  51951. * @returns a boolean indicating if the animation has ended
  51952. */
  51953. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51954. if (weight === void 0) { weight = -1.0; }
  51955. var targetPropertyPath = this._animation.targetPropertyPath;
  51956. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51957. this._stopped = true;
  51958. return false;
  51959. }
  51960. var returnValue = true;
  51961. var keys = this._animation.getKeys();
  51962. // Adding a start key at frame 0 if missing
  51963. if (keys[0].frame !== 0) {
  51964. var newKey = { frame: 0, value: keys[0].value };
  51965. keys.splice(0, 0, newKey);
  51966. }
  51967. // Check limits
  51968. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51969. from = keys[0].frame;
  51970. }
  51971. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51972. to = keys[keys.length - 1].frame;
  51973. }
  51974. //to and from cannot be the same key
  51975. if (from === to) {
  51976. if (from > keys[0].frame) {
  51977. from--;
  51978. }
  51979. else if (to < keys[keys.length - 1].frame) {
  51980. to++;
  51981. }
  51982. }
  51983. // Compute ratio
  51984. var range = to - from;
  51985. var offsetValue;
  51986. // ratio represents the frame delta between from and to
  51987. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51988. var highLimitValue = 0;
  51989. this._previousDelay = delay;
  51990. this._previousRatio = ratio;
  51991. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  51992. returnValue = false;
  51993. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51994. }
  51995. else {
  51996. // Get max value if required
  51997. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51998. var keyOffset = to.toString() + from.toString();
  51999. if (!this._offsetsCache[keyOffset]) {
  52000. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52001. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52002. switch (this._animation.dataType) {
  52003. // Float
  52004. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52005. this._offsetsCache[keyOffset] = toValue - fromValue;
  52006. break;
  52007. // Quaternion
  52008. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52009. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52010. break;
  52011. // Vector3
  52012. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52013. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52014. // Vector2
  52015. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52016. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52017. // Size
  52018. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52019. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52020. // Color3
  52021. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52022. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52023. default:
  52024. break;
  52025. }
  52026. this._highLimitsCache[keyOffset] = toValue;
  52027. }
  52028. highLimitValue = this._highLimitsCache[keyOffset];
  52029. offsetValue = this._offsetsCache[keyOffset];
  52030. }
  52031. }
  52032. if (offsetValue === undefined) {
  52033. switch (this._animation.dataType) {
  52034. // Float
  52035. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52036. offsetValue = 0;
  52037. break;
  52038. // Quaternion
  52039. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52040. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52041. break;
  52042. // Vector3
  52043. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52044. offsetValue = BABYLON.Vector3.Zero();
  52045. break;
  52046. // Vector2
  52047. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52048. offsetValue = BABYLON.Vector2.Zero();
  52049. break;
  52050. // Size
  52051. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52052. offsetValue = BABYLON.Size.Zero();
  52053. break;
  52054. // Color3
  52055. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52056. offsetValue = BABYLON.Color3.Black();
  52057. }
  52058. }
  52059. // Compute value
  52060. var repeatCount = (ratio / range) >> 0;
  52061. var currentFrame = returnValue ? from + ratio % range : to;
  52062. // Need to normalize?
  52063. if (this._host && this._host.syncRoot) {
  52064. var syncRoot = this._host.syncRoot;
  52065. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52066. currentFrame = from + (to - from) * hostNormalizedFrame;
  52067. }
  52068. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52069. // Set value
  52070. this.setValue(currentValue, weight);
  52071. // Check events
  52072. var events = this._animation.getEvents();
  52073. for (var index = 0; index < events.length; index++) {
  52074. // Make sure current frame has passed event frame and that event frame is within the current range
  52075. // Also, handle both forward and reverse animations
  52076. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52077. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52078. var event = events[index];
  52079. if (!event.isDone) {
  52080. // If event should be done only once, remove it.
  52081. if (event.onlyOnce) {
  52082. events.splice(index, 1);
  52083. index--;
  52084. }
  52085. event.isDone = true;
  52086. event.action();
  52087. } // Don't do anything if the event has already be done.
  52088. }
  52089. else if (events[index].isDone && !events[index].onlyOnce) {
  52090. // reset event, the animation is looping
  52091. events[index].isDone = false;
  52092. }
  52093. }
  52094. if (!returnValue) {
  52095. this._stopped = true;
  52096. }
  52097. return returnValue;
  52098. };
  52099. return RuntimeAnimation;
  52100. }());
  52101. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52102. })(BABYLON || (BABYLON = {}));
  52103. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52104. var BABYLON;
  52105. (function (BABYLON) {
  52106. var Animatable = /** @class */ (function () {
  52107. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52108. if (fromFrame === void 0) { fromFrame = 0; }
  52109. if (toFrame === void 0) { toFrame = 100; }
  52110. if (loopAnimation === void 0) { loopAnimation = false; }
  52111. if (speedRatio === void 0) { speedRatio = 1.0; }
  52112. this.target = target;
  52113. this.fromFrame = fromFrame;
  52114. this.toFrame = toFrame;
  52115. this.loopAnimation = loopAnimation;
  52116. this.onAnimationEnd = onAnimationEnd;
  52117. this._localDelayOffset = null;
  52118. this._pausedDelay = null;
  52119. this._runtimeAnimations = new Array();
  52120. this._paused = false;
  52121. this._speedRatio = 1;
  52122. this._weight = -1.0;
  52123. this.animationStarted = false;
  52124. this._scene = scene;
  52125. if (animations) {
  52126. this.appendAnimations(target, animations);
  52127. }
  52128. this._speedRatio = speedRatio;
  52129. scene._activeAnimatables.push(this);
  52130. }
  52131. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52132. /**
  52133. * Gets the root Animatable used to synchronize and normalize animations
  52134. */
  52135. get: function () {
  52136. return this._syncRoot;
  52137. },
  52138. enumerable: true,
  52139. configurable: true
  52140. });
  52141. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52142. /**
  52143. * Gets the current frame of the first RuntimeAnimation
  52144. * Used to synchronize Animatables
  52145. */
  52146. get: function () {
  52147. if (this._runtimeAnimations.length === 0) {
  52148. return 0;
  52149. }
  52150. return this._runtimeAnimations[0].currentFrame;
  52151. },
  52152. enumerable: true,
  52153. configurable: true
  52154. });
  52155. Object.defineProperty(Animatable.prototype, "weight", {
  52156. /**
  52157. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52158. */
  52159. get: function () {
  52160. return this._weight;
  52161. },
  52162. set: function (value) {
  52163. if (value === -1) { // -1 is ok and means no weight
  52164. this._weight = -1;
  52165. return;
  52166. }
  52167. // Else weight must be in [0, 1] range
  52168. this._weight = Math.min(Math.max(value, 0), 1.0);
  52169. },
  52170. enumerable: true,
  52171. configurable: true
  52172. });
  52173. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52174. /**
  52175. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52176. */
  52177. get: function () {
  52178. return this._speedRatio;
  52179. },
  52180. set: function (value) {
  52181. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52182. var animation = this._runtimeAnimations[index];
  52183. animation._prepareForSpeedRatioChange(value);
  52184. }
  52185. this._speedRatio = value;
  52186. },
  52187. enumerable: true,
  52188. configurable: true
  52189. });
  52190. // Methods
  52191. /**
  52192. * Synchronize and normalize current Animatable with a source Animatable
  52193. * This is useful when using animation weights and when animations are not of the same length
  52194. * @param root defines the root Animatable to synchronize with
  52195. * @returns the current Animatable
  52196. */
  52197. Animatable.prototype.syncWith = function (root) {
  52198. this._syncRoot = root;
  52199. if (root) {
  52200. // Make sure this animatable will animate after the root
  52201. var index = this._scene._activeAnimatables.indexOf(this);
  52202. if (index > -1) {
  52203. this._scene._activeAnimatables.splice(index, 1);
  52204. this._scene._activeAnimatables.push(this);
  52205. }
  52206. }
  52207. return this;
  52208. };
  52209. Animatable.prototype.getAnimations = function () {
  52210. return this._runtimeAnimations;
  52211. };
  52212. Animatable.prototype.appendAnimations = function (target, animations) {
  52213. for (var index = 0; index < animations.length; index++) {
  52214. var animation = animations[index];
  52215. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52216. }
  52217. };
  52218. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52219. var runtimeAnimations = this._runtimeAnimations;
  52220. for (var index = 0; index < runtimeAnimations.length; index++) {
  52221. if (runtimeAnimations[index].animation.targetProperty === property) {
  52222. return runtimeAnimations[index].animation;
  52223. }
  52224. }
  52225. return null;
  52226. };
  52227. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52228. var runtimeAnimations = this._runtimeAnimations;
  52229. for (var index = 0; index < runtimeAnimations.length; index++) {
  52230. if (runtimeAnimations[index].animation.targetProperty === property) {
  52231. return runtimeAnimations[index];
  52232. }
  52233. }
  52234. return null;
  52235. };
  52236. Animatable.prototype.reset = function () {
  52237. var runtimeAnimations = this._runtimeAnimations;
  52238. for (var index = 0; index < runtimeAnimations.length; index++) {
  52239. runtimeAnimations[index].reset(true);
  52240. }
  52241. this._localDelayOffset = null;
  52242. this._pausedDelay = null;
  52243. };
  52244. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52245. var runtimeAnimations = this._runtimeAnimations;
  52246. for (var index = 0; index < runtimeAnimations.length; index++) {
  52247. runtimeAnimations[index].animation.enableBlending = true;
  52248. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52249. }
  52250. };
  52251. Animatable.prototype.disableBlending = function () {
  52252. var runtimeAnimations = this._runtimeAnimations;
  52253. for (var index = 0; index < runtimeAnimations.length; index++) {
  52254. runtimeAnimations[index].animation.enableBlending = false;
  52255. }
  52256. };
  52257. Animatable.prototype.goToFrame = function (frame) {
  52258. var runtimeAnimations = this._runtimeAnimations;
  52259. if (runtimeAnimations[0]) {
  52260. var fps = runtimeAnimations[0].animation.framePerSecond;
  52261. var currentFrame = runtimeAnimations[0].currentFrame;
  52262. var adjustTime = frame - currentFrame;
  52263. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52264. if (this._localDelayOffset === null) {
  52265. this._localDelayOffset = 0;
  52266. }
  52267. this._localDelayOffset -= delay;
  52268. }
  52269. for (var index = 0; index < runtimeAnimations.length; index++) {
  52270. runtimeAnimations[index].goToFrame(frame);
  52271. }
  52272. };
  52273. Animatable.prototype.pause = function () {
  52274. if (this._paused) {
  52275. return;
  52276. }
  52277. this._paused = true;
  52278. };
  52279. Animatable.prototype.restart = function () {
  52280. this._paused = false;
  52281. };
  52282. Animatable.prototype.stop = function (animationName) {
  52283. if (animationName) {
  52284. var idx = this._scene._activeAnimatables.indexOf(this);
  52285. if (idx > -1) {
  52286. var runtimeAnimations = this._runtimeAnimations;
  52287. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52288. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52289. continue;
  52290. }
  52291. runtimeAnimations[index].dispose();
  52292. runtimeAnimations.splice(index, 1);
  52293. }
  52294. if (runtimeAnimations.length == 0) {
  52295. this._scene._activeAnimatables.splice(idx, 1);
  52296. if (this.onAnimationEnd) {
  52297. this.onAnimationEnd();
  52298. }
  52299. }
  52300. }
  52301. }
  52302. else {
  52303. var index = this._scene._activeAnimatables.indexOf(this);
  52304. if (index > -1) {
  52305. this._scene._activeAnimatables.splice(index, 1);
  52306. var runtimeAnimations = this._runtimeAnimations;
  52307. for (var index = 0; index < runtimeAnimations.length; index++) {
  52308. runtimeAnimations[index].dispose();
  52309. }
  52310. if (this.onAnimationEnd) {
  52311. this.onAnimationEnd();
  52312. }
  52313. }
  52314. }
  52315. };
  52316. Animatable.prototype._animate = function (delay) {
  52317. if (this._paused) {
  52318. this.animationStarted = false;
  52319. if (this._pausedDelay === null) {
  52320. this._pausedDelay = delay;
  52321. }
  52322. return true;
  52323. }
  52324. if (this._localDelayOffset === null) {
  52325. this._localDelayOffset = delay;
  52326. this._pausedDelay = null;
  52327. }
  52328. else if (this._pausedDelay !== null) {
  52329. this._localDelayOffset += delay - this._pausedDelay;
  52330. this._pausedDelay = null;
  52331. }
  52332. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52333. return true;
  52334. }
  52335. // Animating
  52336. var running = false;
  52337. var runtimeAnimations = this._runtimeAnimations;
  52338. var index;
  52339. for (index = 0; index < runtimeAnimations.length; index++) {
  52340. var animation = runtimeAnimations[index];
  52341. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52342. running = running || isRunning;
  52343. }
  52344. this.animationStarted = running;
  52345. if (!running) {
  52346. // Remove from active animatables
  52347. index = this._scene._activeAnimatables.indexOf(this);
  52348. this._scene._activeAnimatables.splice(index, 1);
  52349. // Dispose all runtime animations
  52350. for (index = 0; index < runtimeAnimations.length; index++) {
  52351. runtimeAnimations[index].dispose();
  52352. }
  52353. }
  52354. if (!running && this.onAnimationEnd) {
  52355. this.onAnimationEnd();
  52356. this.onAnimationEnd = null;
  52357. }
  52358. return running;
  52359. };
  52360. return Animatable;
  52361. }());
  52362. BABYLON.Animatable = Animatable;
  52363. })(BABYLON || (BABYLON = {}));
  52364. //# sourceMappingURL=babylon.animatable.js.map
  52365. var BABYLON;
  52366. (function (BABYLON) {
  52367. var EasingFunction = /** @class */ (function () {
  52368. function EasingFunction() {
  52369. // Properties
  52370. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52371. }
  52372. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52373. get: function () {
  52374. return EasingFunction._EASINGMODE_EASEIN;
  52375. },
  52376. enumerable: true,
  52377. configurable: true
  52378. });
  52379. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52380. get: function () {
  52381. return EasingFunction._EASINGMODE_EASEOUT;
  52382. },
  52383. enumerable: true,
  52384. configurable: true
  52385. });
  52386. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52387. get: function () {
  52388. return EasingFunction._EASINGMODE_EASEINOUT;
  52389. },
  52390. enumerable: true,
  52391. configurable: true
  52392. });
  52393. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52394. var n = Math.min(Math.max(easingMode, 0), 2);
  52395. this._easingMode = n;
  52396. };
  52397. EasingFunction.prototype.getEasingMode = function () {
  52398. return this._easingMode;
  52399. };
  52400. EasingFunction.prototype.easeInCore = function (gradient) {
  52401. throw new Error('You must implement this method');
  52402. };
  52403. EasingFunction.prototype.ease = function (gradient) {
  52404. switch (this._easingMode) {
  52405. case EasingFunction.EASINGMODE_EASEIN:
  52406. return this.easeInCore(gradient);
  52407. case EasingFunction.EASINGMODE_EASEOUT:
  52408. return (1 - this.easeInCore(1 - gradient));
  52409. }
  52410. if (gradient >= 0.5) {
  52411. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52412. }
  52413. return (this.easeInCore(gradient * 2) * 0.5);
  52414. };
  52415. //Statics
  52416. EasingFunction._EASINGMODE_EASEIN = 0;
  52417. EasingFunction._EASINGMODE_EASEOUT = 1;
  52418. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52419. return EasingFunction;
  52420. }());
  52421. BABYLON.EasingFunction = EasingFunction;
  52422. var CircleEase = /** @class */ (function (_super) {
  52423. __extends(CircleEase, _super);
  52424. function CircleEase() {
  52425. return _super !== null && _super.apply(this, arguments) || this;
  52426. }
  52427. CircleEase.prototype.easeInCore = function (gradient) {
  52428. gradient = Math.max(0, Math.min(1, gradient));
  52429. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52430. };
  52431. return CircleEase;
  52432. }(EasingFunction));
  52433. BABYLON.CircleEase = CircleEase;
  52434. var BackEase = /** @class */ (function (_super) {
  52435. __extends(BackEase, _super);
  52436. function BackEase(amplitude) {
  52437. if (amplitude === void 0) { amplitude = 1; }
  52438. var _this = _super.call(this) || this;
  52439. _this.amplitude = amplitude;
  52440. return _this;
  52441. }
  52442. BackEase.prototype.easeInCore = function (gradient) {
  52443. var num = Math.max(0, this.amplitude);
  52444. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52445. };
  52446. return BackEase;
  52447. }(EasingFunction));
  52448. BABYLON.BackEase = BackEase;
  52449. var BounceEase = /** @class */ (function (_super) {
  52450. __extends(BounceEase, _super);
  52451. function BounceEase(bounces, bounciness) {
  52452. if (bounces === void 0) { bounces = 3; }
  52453. if (bounciness === void 0) { bounciness = 2; }
  52454. var _this = _super.call(this) || this;
  52455. _this.bounces = bounces;
  52456. _this.bounciness = bounciness;
  52457. return _this;
  52458. }
  52459. BounceEase.prototype.easeInCore = function (gradient) {
  52460. var y = Math.max(0.0, this.bounces);
  52461. var bounciness = this.bounciness;
  52462. if (bounciness <= 1.0) {
  52463. bounciness = 1.001;
  52464. }
  52465. var num9 = Math.pow(bounciness, y);
  52466. var num5 = 1.0 - bounciness;
  52467. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52468. var num15 = gradient * num4;
  52469. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52470. var num3 = Math.floor(num65);
  52471. var num13 = num3 + 1.0;
  52472. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52473. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52474. var num7 = (num8 + num12) * 0.5;
  52475. var num6 = gradient - num7;
  52476. var num2 = num7 - num8;
  52477. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52478. };
  52479. return BounceEase;
  52480. }(EasingFunction));
  52481. BABYLON.BounceEase = BounceEase;
  52482. var CubicEase = /** @class */ (function (_super) {
  52483. __extends(CubicEase, _super);
  52484. function CubicEase() {
  52485. return _super !== null && _super.apply(this, arguments) || this;
  52486. }
  52487. CubicEase.prototype.easeInCore = function (gradient) {
  52488. return (gradient * gradient * gradient);
  52489. };
  52490. return CubicEase;
  52491. }(EasingFunction));
  52492. BABYLON.CubicEase = CubicEase;
  52493. var ElasticEase = /** @class */ (function (_super) {
  52494. __extends(ElasticEase, _super);
  52495. function ElasticEase(oscillations, springiness) {
  52496. if (oscillations === void 0) { oscillations = 3; }
  52497. if (springiness === void 0) { springiness = 3; }
  52498. var _this = _super.call(this) || this;
  52499. _this.oscillations = oscillations;
  52500. _this.springiness = springiness;
  52501. return _this;
  52502. }
  52503. ElasticEase.prototype.easeInCore = function (gradient) {
  52504. var num2;
  52505. var num3 = Math.max(0.0, this.oscillations);
  52506. var num = Math.max(0.0, this.springiness);
  52507. if (num == 0) {
  52508. num2 = gradient;
  52509. }
  52510. else {
  52511. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52512. }
  52513. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52514. };
  52515. return ElasticEase;
  52516. }(EasingFunction));
  52517. BABYLON.ElasticEase = ElasticEase;
  52518. var ExponentialEase = /** @class */ (function (_super) {
  52519. __extends(ExponentialEase, _super);
  52520. function ExponentialEase(exponent) {
  52521. if (exponent === void 0) { exponent = 2; }
  52522. var _this = _super.call(this) || this;
  52523. _this.exponent = exponent;
  52524. return _this;
  52525. }
  52526. ExponentialEase.prototype.easeInCore = function (gradient) {
  52527. if (this.exponent <= 0) {
  52528. return gradient;
  52529. }
  52530. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52531. };
  52532. return ExponentialEase;
  52533. }(EasingFunction));
  52534. BABYLON.ExponentialEase = ExponentialEase;
  52535. var PowerEase = /** @class */ (function (_super) {
  52536. __extends(PowerEase, _super);
  52537. function PowerEase(power) {
  52538. if (power === void 0) { power = 2; }
  52539. var _this = _super.call(this) || this;
  52540. _this.power = power;
  52541. return _this;
  52542. }
  52543. PowerEase.prototype.easeInCore = function (gradient) {
  52544. var y = Math.max(0.0, this.power);
  52545. return Math.pow(gradient, y);
  52546. };
  52547. return PowerEase;
  52548. }(EasingFunction));
  52549. BABYLON.PowerEase = PowerEase;
  52550. var QuadraticEase = /** @class */ (function (_super) {
  52551. __extends(QuadraticEase, _super);
  52552. function QuadraticEase() {
  52553. return _super !== null && _super.apply(this, arguments) || this;
  52554. }
  52555. QuadraticEase.prototype.easeInCore = function (gradient) {
  52556. return (gradient * gradient);
  52557. };
  52558. return QuadraticEase;
  52559. }(EasingFunction));
  52560. BABYLON.QuadraticEase = QuadraticEase;
  52561. var QuarticEase = /** @class */ (function (_super) {
  52562. __extends(QuarticEase, _super);
  52563. function QuarticEase() {
  52564. return _super !== null && _super.apply(this, arguments) || this;
  52565. }
  52566. QuarticEase.prototype.easeInCore = function (gradient) {
  52567. return (gradient * gradient * gradient * gradient);
  52568. };
  52569. return QuarticEase;
  52570. }(EasingFunction));
  52571. BABYLON.QuarticEase = QuarticEase;
  52572. var QuinticEase = /** @class */ (function (_super) {
  52573. __extends(QuinticEase, _super);
  52574. function QuinticEase() {
  52575. return _super !== null && _super.apply(this, arguments) || this;
  52576. }
  52577. QuinticEase.prototype.easeInCore = function (gradient) {
  52578. return (gradient * gradient * gradient * gradient * gradient);
  52579. };
  52580. return QuinticEase;
  52581. }(EasingFunction));
  52582. BABYLON.QuinticEase = QuinticEase;
  52583. var SineEase = /** @class */ (function (_super) {
  52584. __extends(SineEase, _super);
  52585. function SineEase() {
  52586. return _super !== null && _super.apply(this, arguments) || this;
  52587. }
  52588. SineEase.prototype.easeInCore = function (gradient) {
  52589. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52590. };
  52591. return SineEase;
  52592. }(EasingFunction));
  52593. BABYLON.SineEase = SineEase;
  52594. var BezierCurveEase = /** @class */ (function (_super) {
  52595. __extends(BezierCurveEase, _super);
  52596. function BezierCurveEase(x1, y1, x2, y2) {
  52597. if (x1 === void 0) { x1 = 0; }
  52598. if (y1 === void 0) { y1 = 0; }
  52599. if (x2 === void 0) { x2 = 1; }
  52600. if (y2 === void 0) { y2 = 1; }
  52601. var _this = _super.call(this) || this;
  52602. _this.x1 = x1;
  52603. _this.y1 = y1;
  52604. _this.x2 = x2;
  52605. _this.y2 = y2;
  52606. return _this;
  52607. }
  52608. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52609. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52610. };
  52611. return BezierCurveEase;
  52612. }(EasingFunction));
  52613. BABYLON.BezierCurveEase = BezierCurveEase;
  52614. })(BABYLON || (BABYLON = {}));
  52615. //# sourceMappingURL=babylon.easing.js.map
  52616. var BABYLON;
  52617. (function (BABYLON) {
  52618. /**
  52619. * A Condition applied to an Action
  52620. */
  52621. var Condition = /** @class */ (function () {
  52622. /**
  52623. * Creates a new Condition
  52624. * @param actionManager the manager of the action the condition is applied to
  52625. */
  52626. function Condition(actionManager) {
  52627. this._actionManager = actionManager;
  52628. }
  52629. /**
  52630. * Check if the current condition is valid
  52631. * @returns a boolean
  52632. */
  52633. Condition.prototype.isValid = function () {
  52634. return true;
  52635. };
  52636. /**
  52637. * Internal only
  52638. * @hidden
  52639. */
  52640. Condition.prototype._getProperty = function (propertyPath) {
  52641. return this._actionManager._getProperty(propertyPath);
  52642. };
  52643. /**
  52644. * Internal only
  52645. * @hidden
  52646. */
  52647. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52648. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52649. };
  52650. /**
  52651. * Serialize placeholder for child classes
  52652. * @returns the serialized object
  52653. */
  52654. Condition.prototype.serialize = function () {
  52655. };
  52656. /**
  52657. * Internal only
  52658. * @hidden
  52659. */
  52660. Condition.prototype._serialize = function (serializedCondition) {
  52661. return {
  52662. type: 2,
  52663. children: [],
  52664. name: serializedCondition.name,
  52665. properties: serializedCondition.properties
  52666. };
  52667. };
  52668. return Condition;
  52669. }());
  52670. BABYLON.Condition = Condition;
  52671. /**
  52672. * Defines specific conditional operators as extensions of Condition
  52673. */
  52674. var ValueCondition = /** @class */ (function (_super) {
  52675. __extends(ValueCondition, _super);
  52676. /**
  52677. * Creates a new ValueCondition
  52678. * @param actionManager manager for the action the condition applies to
  52679. * @param target for the action
  52680. * @param propertyPath path to specify the property of the target the conditional operator uses
  52681. * @param value the value compared by the conditional operator against the current value of the property
  52682. * @param operator the conditional operator, default ValueCondition.IsEqual
  52683. */
  52684. function ValueCondition(actionManager, target,
  52685. /** path to specify the property of the target the conditional operator uses */
  52686. propertyPath,
  52687. /** the value compared by the conditional operator against the current value of the property */
  52688. value,
  52689. /** the conditional operator, default ValueCondition.IsEqual */
  52690. operator) {
  52691. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52692. var _this = _super.call(this, actionManager) || this;
  52693. _this.propertyPath = propertyPath;
  52694. _this.value = value;
  52695. _this.operator = operator;
  52696. _this._target = target;
  52697. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52698. _this._property = _this._getProperty(_this.propertyPath);
  52699. return _this;
  52700. }
  52701. Object.defineProperty(ValueCondition, "IsEqual", {
  52702. /**
  52703. * returns the number for IsEqual
  52704. */
  52705. get: function () {
  52706. return ValueCondition._IsEqual;
  52707. },
  52708. enumerable: true,
  52709. configurable: true
  52710. });
  52711. Object.defineProperty(ValueCondition, "IsDifferent", {
  52712. /**
  52713. * Returns the number for IsDifferent
  52714. */
  52715. get: function () {
  52716. return ValueCondition._IsDifferent;
  52717. },
  52718. enumerable: true,
  52719. configurable: true
  52720. });
  52721. Object.defineProperty(ValueCondition, "IsGreater", {
  52722. /**
  52723. * Returns the number for IsGreater
  52724. */
  52725. get: function () {
  52726. return ValueCondition._IsGreater;
  52727. },
  52728. enumerable: true,
  52729. configurable: true
  52730. });
  52731. Object.defineProperty(ValueCondition, "IsLesser", {
  52732. /**
  52733. * Returns the number for IsLesser
  52734. */
  52735. get: function () {
  52736. return ValueCondition._IsLesser;
  52737. },
  52738. enumerable: true,
  52739. configurable: true
  52740. });
  52741. /**
  52742. * Compares the given value with the property value for the specified conditional operator
  52743. * @returns the result of the comparison
  52744. */
  52745. ValueCondition.prototype.isValid = function () {
  52746. switch (this.operator) {
  52747. case ValueCondition.IsGreater:
  52748. return this._effectiveTarget[this._property] > this.value;
  52749. case ValueCondition.IsLesser:
  52750. return this._effectiveTarget[this._property] < this.value;
  52751. case ValueCondition.IsEqual:
  52752. case ValueCondition.IsDifferent:
  52753. var check;
  52754. if (this.value.equals) {
  52755. check = this.value.equals(this._effectiveTarget[this._property]);
  52756. }
  52757. else {
  52758. check = this.value === this._effectiveTarget[this._property];
  52759. }
  52760. return this.operator === ValueCondition.IsEqual ? check : !check;
  52761. }
  52762. return false;
  52763. };
  52764. /**
  52765. * Serialize the ValueCondition into a JSON compatible object
  52766. * @returns serialization object
  52767. */
  52768. ValueCondition.prototype.serialize = function () {
  52769. return this._serialize({
  52770. name: "ValueCondition",
  52771. properties: [
  52772. BABYLON.Action._GetTargetProperty(this._target),
  52773. { name: "propertyPath", value: this.propertyPath },
  52774. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52775. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52776. ]
  52777. });
  52778. };
  52779. /**
  52780. * Gets the name of the conditional operator for the ValueCondition
  52781. * @param operator the conditional operator
  52782. * @returns the name
  52783. */
  52784. ValueCondition.GetOperatorName = function (operator) {
  52785. switch (operator) {
  52786. case ValueCondition._IsEqual: return "IsEqual";
  52787. case ValueCondition._IsDifferent: return "IsDifferent";
  52788. case ValueCondition._IsGreater: return "IsGreater";
  52789. case ValueCondition._IsLesser: return "IsLesser";
  52790. default: return "";
  52791. }
  52792. };
  52793. /**
  52794. * Internal only
  52795. * @hidden
  52796. */
  52797. ValueCondition._IsEqual = 0;
  52798. /**
  52799. * Internal only
  52800. * @hidden
  52801. */
  52802. ValueCondition._IsDifferent = 1;
  52803. /**
  52804. * Internal only
  52805. * @hidden
  52806. */
  52807. ValueCondition._IsGreater = 2;
  52808. /**
  52809. * Internal only
  52810. * @hidden
  52811. */
  52812. ValueCondition._IsLesser = 3;
  52813. return ValueCondition;
  52814. }(Condition));
  52815. BABYLON.ValueCondition = ValueCondition;
  52816. /**
  52817. * Defines a predicate condition as an extension of Condition
  52818. */
  52819. var PredicateCondition = /** @class */ (function (_super) {
  52820. __extends(PredicateCondition, _super);
  52821. /**
  52822. * Creates a new PredicateCondition
  52823. * @param actionManager manager for the action the condition applies to
  52824. * @param predicate defines the predicate function used to validate the condition
  52825. */
  52826. function PredicateCondition(actionManager,
  52827. /** defines the predicate function used to validate the condition */
  52828. predicate) {
  52829. var _this = _super.call(this, actionManager) || this;
  52830. _this.predicate = predicate;
  52831. return _this;
  52832. }
  52833. /**
  52834. * @returns the validity of the predicate condition
  52835. */
  52836. PredicateCondition.prototype.isValid = function () {
  52837. return this.predicate();
  52838. };
  52839. return PredicateCondition;
  52840. }(Condition));
  52841. BABYLON.PredicateCondition = PredicateCondition;
  52842. /**
  52843. * Defines a state condition as an extension of Condition
  52844. */
  52845. var StateCondition = /** @class */ (function (_super) {
  52846. __extends(StateCondition, _super);
  52847. /**
  52848. * Creates a new StateCondition
  52849. * @param actionManager manager for the action the condition applies to
  52850. * @param target of the condition
  52851. * @param value to compare with target state
  52852. */
  52853. function StateCondition(actionManager, target, value) {
  52854. var _this = _super.call(this, actionManager) || this;
  52855. _this.value = value;
  52856. _this._target = target;
  52857. return _this;
  52858. }
  52859. /**
  52860. * @returns the validity of the state
  52861. */
  52862. StateCondition.prototype.isValid = function () {
  52863. return this._target.state === this.value;
  52864. };
  52865. /**
  52866. * Serialize the StateCondition into a JSON compatible object
  52867. * @returns serialization object
  52868. */
  52869. StateCondition.prototype.serialize = function () {
  52870. return this._serialize({
  52871. name: "StateCondition",
  52872. properties: [
  52873. BABYLON.Action._GetTargetProperty(this._target),
  52874. { name: "value", value: this.value }
  52875. ]
  52876. });
  52877. };
  52878. return StateCondition;
  52879. }(Condition));
  52880. BABYLON.StateCondition = StateCondition;
  52881. })(BABYLON || (BABYLON = {}));
  52882. //# sourceMappingURL=babylon.condition.js.map
  52883. var BABYLON;
  52884. (function (BABYLON) {
  52885. /**
  52886. * The action to be carried out following a trigger
  52887. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52888. */
  52889. var Action = /** @class */ (function () {
  52890. /**
  52891. * Creates a new Action
  52892. * @param triggerOptions the trigger, with or without parameters, for the action
  52893. * @param condition an optional determinant of action
  52894. */
  52895. function Action(
  52896. /** the trigger, with or without parameters, for the action */
  52897. triggerOptions, condition) {
  52898. this.triggerOptions = triggerOptions;
  52899. /**
  52900. * An event triggered prior to action being executed.
  52901. */
  52902. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52903. if (triggerOptions.parameter) {
  52904. this.trigger = triggerOptions.trigger;
  52905. this._triggerParameter = triggerOptions.parameter;
  52906. }
  52907. else {
  52908. this.trigger = triggerOptions;
  52909. }
  52910. this._nextActiveAction = this;
  52911. this._condition = condition;
  52912. }
  52913. /**
  52914. * Internal only
  52915. * @hidden
  52916. */
  52917. Action.prototype._prepare = function () {
  52918. };
  52919. /**
  52920. * Gets the trigger parameters
  52921. * @returns the trigger parameters
  52922. */
  52923. Action.prototype.getTriggerParameter = function () {
  52924. return this._triggerParameter;
  52925. };
  52926. /**
  52927. * Internal only - executes current action event
  52928. * @hidden
  52929. */
  52930. Action.prototype._executeCurrent = function (evt) {
  52931. if (this._nextActiveAction._condition) {
  52932. var condition = this._nextActiveAction._condition;
  52933. var currentRenderId = this._actionManager.getScene().getRenderId();
  52934. // We cache the current evaluation for the current frame
  52935. if (condition._evaluationId === currentRenderId) {
  52936. if (!condition._currentResult) {
  52937. return;
  52938. }
  52939. }
  52940. else {
  52941. condition._evaluationId = currentRenderId;
  52942. if (!condition.isValid()) {
  52943. condition._currentResult = false;
  52944. return;
  52945. }
  52946. condition._currentResult = true;
  52947. }
  52948. }
  52949. this.onBeforeExecuteObservable.notifyObservers(this);
  52950. this._nextActiveAction.execute(evt);
  52951. this.skipToNextActiveAction();
  52952. };
  52953. /**
  52954. * Execute placeholder for child classes
  52955. * @param evt optional action event
  52956. */
  52957. Action.prototype.execute = function (evt) {
  52958. };
  52959. /**
  52960. * Skips to next active action
  52961. */
  52962. Action.prototype.skipToNextActiveAction = function () {
  52963. if (this._nextActiveAction._child) {
  52964. if (!this._nextActiveAction._child._actionManager) {
  52965. this._nextActiveAction._child._actionManager = this._actionManager;
  52966. }
  52967. this._nextActiveAction = this._nextActiveAction._child;
  52968. }
  52969. else {
  52970. this._nextActiveAction = this;
  52971. }
  52972. };
  52973. /**
  52974. * Adds action to chain of actions, may be a DoNothingAction
  52975. * @param action defines the next action to execute
  52976. * @returns The action passed in
  52977. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52978. */
  52979. Action.prototype.then = function (action) {
  52980. this._child = action;
  52981. action._actionManager = this._actionManager;
  52982. action._prepare();
  52983. return action;
  52984. };
  52985. /**
  52986. * Internal only
  52987. * @hidden
  52988. */
  52989. Action.prototype._getProperty = function (propertyPath) {
  52990. return this._actionManager._getProperty(propertyPath);
  52991. };
  52992. /**
  52993. * Internal only
  52994. * @hidden
  52995. */
  52996. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52997. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52998. };
  52999. /**
  53000. * Serialize placeholder for child classes
  53001. * @param parent of child
  53002. * @returns the serialized object
  53003. */
  53004. Action.prototype.serialize = function (parent) {
  53005. };
  53006. /**
  53007. * Internal only called by serialize
  53008. * @hidden
  53009. */
  53010. Action.prototype._serialize = function (serializedAction, parent) {
  53011. var serializationObject = {
  53012. type: 1,
  53013. children: [],
  53014. name: serializedAction.name,
  53015. properties: serializedAction.properties || []
  53016. };
  53017. // Serialize child
  53018. if (this._child) {
  53019. this._child.serialize(serializationObject);
  53020. }
  53021. // Check if "this" has a condition
  53022. if (this._condition) {
  53023. var serializedCondition = this._condition.serialize();
  53024. serializedCondition.children.push(serializationObject);
  53025. if (parent) {
  53026. parent.children.push(serializedCondition);
  53027. }
  53028. return serializedCondition;
  53029. }
  53030. if (parent) {
  53031. parent.children.push(serializationObject);
  53032. }
  53033. return serializationObject;
  53034. };
  53035. /**
  53036. * Internal only
  53037. * @hidden
  53038. */
  53039. Action._SerializeValueAsString = function (value) {
  53040. if (typeof value === "number") {
  53041. return value.toString();
  53042. }
  53043. if (typeof value === "boolean") {
  53044. return value ? "true" : "false";
  53045. }
  53046. if (value instanceof BABYLON.Vector2) {
  53047. return value.x + ", " + value.y;
  53048. }
  53049. if (value instanceof BABYLON.Vector3) {
  53050. return value.x + ", " + value.y + ", " + value.z;
  53051. }
  53052. if (value instanceof BABYLON.Color3) {
  53053. return value.r + ", " + value.g + ", " + value.b;
  53054. }
  53055. if (value instanceof BABYLON.Color4) {
  53056. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53057. }
  53058. return value; // string
  53059. };
  53060. /**
  53061. * Internal only
  53062. * @hidden
  53063. */
  53064. Action._GetTargetProperty = function (target) {
  53065. return {
  53066. name: "target",
  53067. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53068. : target instanceof BABYLON.Light ? "LightProperties"
  53069. : target instanceof BABYLON.Camera ? "CameraProperties"
  53070. : "SceneProperties",
  53071. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53072. };
  53073. };
  53074. return Action;
  53075. }());
  53076. BABYLON.Action = Action;
  53077. })(BABYLON || (BABYLON = {}));
  53078. //# sourceMappingURL=babylon.action.js.map
  53079. var BABYLON;
  53080. (function (BABYLON) {
  53081. /**
  53082. * ActionEvent is the event being sent when an action is triggered.
  53083. */
  53084. var ActionEvent = /** @class */ (function () {
  53085. /**
  53086. * Creates a new ActionEvent
  53087. * @param source The mesh or sprite that triggered the action
  53088. * @param pointerX The X mouse cursor position at the time of the event
  53089. * @param pointerY The Y mouse cursor position at the time of the event
  53090. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53091. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53092. * @param additionalData additional data for the event
  53093. */
  53094. function ActionEvent(
  53095. /** The mesh or sprite that triggered the action */
  53096. source,
  53097. /** The X mouse cursor position at the time of the event */
  53098. pointerX,
  53099. /** The Y mouse cursor position at the time of the event */
  53100. pointerY,
  53101. /** The mesh that is currently pointed at (can be null) */
  53102. meshUnderPointer,
  53103. /** the original (browser) event that triggered the ActionEvent */
  53104. sourceEvent,
  53105. /** additional data for the event */
  53106. additionalData) {
  53107. this.source = source;
  53108. this.pointerX = pointerX;
  53109. this.pointerY = pointerY;
  53110. this.meshUnderPointer = meshUnderPointer;
  53111. this.sourceEvent = sourceEvent;
  53112. this.additionalData = additionalData;
  53113. }
  53114. /**
  53115. * Helper function to auto-create an ActionEvent from a source mesh.
  53116. * @param source The source mesh that triggered the event
  53117. * @param evt The original (browser) event
  53118. * @param additionalData additional data for the event
  53119. * @returns the new ActionEvent
  53120. */
  53121. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53122. var scene = source.getScene();
  53123. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53124. };
  53125. /**
  53126. * Helper function to auto-create an ActionEvent from a source sprite
  53127. * @param source The source sprite that triggered the event
  53128. * @param scene Scene associated with the sprite
  53129. * @param evt The original (browser) event
  53130. * @param additionalData additional data for the event
  53131. * @returns the new ActionEvent
  53132. */
  53133. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53134. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53135. };
  53136. /**
  53137. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53138. * @param scene the scene where the event occurred
  53139. * @param evt The original (browser) event
  53140. * @returns the new ActionEvent
  53141. */
  53142. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53143. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53144. };
  53145. /**
  53146. * Helper function to auto-create an ActionEvent from a primitive
  53147. * @param prim defines the target primitive
  53148. * @param pointerPos defines the pointer position
  53149. * @param evt The original (browser) event
  53150. * @param additionalData additional data for the event
  53151. * @returns the new ActionEvent
  53152. */
  53153. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53154. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53155. };
  53156. return ActionEvent;
  53157. }());
  53158. BABYLON.ActionEvent = ActionEvent;
  53159. /**
  53160. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53161. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53162. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53163. */
  53164. var ActionManager = /** @class */ (function () {
  53165. /**
  53166. * Creates a new action manager
  53167. * @param scene defines the hosting scene
  53168. */
  53169. function ActionManager(scene) {
  53170. // Members
  53171. /** Gets the list of actions */
  53172. this.actions = new Array();
  53173. /** Gets the cursor to use when hovering items */
  53174. this.hoverCursor = '';
  53175. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53176. scene._actionManagers.push(this);
  53177. }
  53178. Object.defineProperty(ActionManager, "NothingTrigger", {
  53179. /**
  53180. * Nothing
  53181. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53182. */
  53183. get: function () {
  53184. return ActionManager._NothingTrigger;
  53185. },
  53186. enumerable: true,
  53187. configurable: true
  53188. });
  53189. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53190. /**
  53191. * On pick
  53192. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53193. */
  53194. get: function () {
  53195. return ActionManager._OnPickTrigger;
  53196. },
  53197. enumerable: true,
  53198. configurable: true
  53199. });
  53200. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53201. /**
  53202. * On left pick
  53203. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53204. */
  53205. get: function () {
  53206. return ActionManager._OnLeftPickTrigger;
  53207. },
  53208. enumerable: true,
  53209. configurable: true
  53210. });
  53211. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53212. /**
  53213. * On right pick
  53214. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53215. */
  53216. get: function () {
  53217. return ActionManager._OnRightPickTrigger;
  53218. },
  53219. enumerable: true,
  53220. configurable: true
  53221. });
  53222. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53223. /**
  53224. * On center pick
  53225. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53226. */
  53227. get: function () {
  53228. return ActionManager._OnCenterPickTrigger;
  53229. },
  53230. enumerable: true,
  53231. configurable: true
  53232. });
  53233. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53234. /**
  53235. * On pick down
  53236. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53237. */
  53238. get: function () {
  53239. return ActionManager._OnPickDownTrigger;
  53240. },
  53241. enumerable: true,
  53242. configurable: true
  53243. });
  53244. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53245. /**
  53246. * On double pick
  53247. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53248. */
  53249. get: function () {
  53250. return ActionManager._OnDoublePickTrigger;
  53251. },
  53252. enumerable: true,
  53253. configurable: true
  53254. });
  53255. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53256. /**
  53257. * On pick up
  53258. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53259. */
  53260. get: function () {
  53261. return ActionManager._OnPickUpTrigger;
  53262. },
  53263. enumerable: true,
  53264. configurable: true
  53265. });
  53266. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53267. /**
  53268. * On pick out.
  53269. * This trigger will only be raised if you also declared a OnPickDown
  53270. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53271. */
  53272. get: function () {
  53273. return ActionManager._OnPickOutTrigger;
  53274. },
  53275. enumerable: true,
  53276. configurable: true
  53277. });
  53278. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53279. /**
  53280. * On long press
  53281. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53282. */
  53283. get: function () {
  53284. return ActionManager._OnLongPressTrigger;
  53285. },
  53286. enumerable: true,
  53287. configurable: true
  53288. });
  53289. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53290. /**
  53291. * On pointer over
  53292. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53293. */
  53294. get: function () {
  53295. return ActionManager._OnPointerOverTrigger;
  53296. },
  53297. enumerable: true,
  53298. configurable: true
  53299. });
  53300. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53301. /**
  53302. * On pointer out
  53303. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53304. */
  53305. get: function () {
  53306. return ActionManager._OnPointerOutTrigger;
  53307. },
  53308. enumerable: true,
  53309. configurable: true
  53310. });
  53311. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53312. /**
  53313. * On every frame
  53314. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53315. */
  53316. get: function () {
  53317. return ActionManager._OnEveryFrameTrigger;
  53318. },
  53319. enumerable: true,
  53320. configurable: true
  53321. });
  53322. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53323. /**
  53324. * On intersection enter
  53325. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53326. */
  53327. get: function () {
  53328. return ActionManager._OnIntersectionEnterTrigger;
  53329. },
  53330. enumerable: true,
  53331. configurable: true
  53332. });
  53333. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53334. /**
  53335. * On intersection exit
  53336. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53337. */
  53338. get: function () {
  53339. return ActionManager._OnIntersectionExitTrigger;
  53340. },
  53341. enumerable: true,
  53342. configurable: true
  53343. });
  53344. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53345. /**
  53346. * On key down
  53347. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53348. */
  53349. get: function () {
  53350. return ActionManager._OnKeyDownTrigger;
  53351. },
  53352. enumerable: true,
  53353. configurable: true
  53354. });
  53355. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53356. /**
  53357. * On key up
  53358. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53359. */
  53360. get: function () {
  53361. return ActionManager._OnKeyUpTrigger;
  53362. },
  53363. enumerable: true,
  53364. configurable: true
  53365. });
  53366. // Methods
  53367. /**
  53368. * Releases all associated resources
  53369. */
  53370. ActionManager.prototype.dispose = function () {
  53371. var index = this._scene._actionManagers.indexOf(this);
  53372. for (var i = 0; i < this.actions.length; i++) {
  53373. var action = this.actions[i];
  53374. ActionManager.Triggers[action.trigger]--;
  53375. if (ActionManager.Triggers[action.trigger] === 0) {
  53376. delete ActionManager.Triggers[action.trigger];
  53377. }
  53378. }
  53379. if (index > -1) {
  53380. this._scene._actionManagers.splice(index, 1);
  53381. }
  53382. };
  53383. /**
  53384. * Gets hosting scene
  53385. * @returns the hosting scene
  53386. */
  53387. ActionManager.prototype.getScene = function () {
  53388. return this._scene;
  53389. };
  53390. /**
  53391. * Does this action manager handles actions of any of the given triggers
  53392. * @param triggers defines the triggers to be tested
  53393. * @return a boolean indicating whether one (or more) of the triggers is handled
  53394. */
  53395. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53396. for (var index = 0; index < this.actions.length; index++) {
  53397. var action = this.actions[index];
  53398. if (triggers.indexOf(action.trigger) > -1) {
  53399. return true;
  53400. }
  53401. }
  53402. return false;
  53403. };
  53404. /**
  53405. * Does this action manager handles actions of a given trigger
  53406. * @param trigger defines the trigger to be tested
  53407. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53408. * @return whether the trigger is handled
  53409. */
  53410. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53411. for (var index = 0; index < this.actions.length; index++) {
  53412. var action = this.actions[index];
  53413. if (action.trigger === trigger) {
  53414. if (parameterPredicate) {
  53415. if (parameterPredicate(action.getTriggerParameter())) {
  53416. return true;
  53417. }
  53418. }
  53419. else {
  53420. return true;
  53421. }
  53422. }
  53423. }
  53424. return false;
  53425. };
  53426. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53427. /**
  53428. * Does this action manager has pointer triggers
  53429. */
  53430. get: function () {
  53431. for (var index = 0; index < this.actions.length; index++) {
  53432. var action = this.actions[index];
  53433. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53434. return true;
  53435. }
  53436. }
  53437. return false;
  53438. },
  53439. enumerable: true,
  53440. configurable: true
  53441. });
  53442. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53443. /**
  53444. * Does this action manager has pick triggers
  53445. */
  53446. get: function () {
  53447. for (var index = 0; index < this.actions.length; index++) {
  53448. var action = this.actions[index];
  53449. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53450. return true;
  53451. }
  53452. }
  53453. return false;
  53454. },
  53455. enumerable: true,
  53456. configurable: true
  53457. });
  53458. Object.defineProperty(ActionManager, "HasTriggers", {
  53459. /**
  53460. * Does exist one action manager with at least one trigger
  53461. **/
  53462. get: function () {
  53463. for (var t in ActionManager.Triggers) {
  53464. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53465. return true;
  53466. }
  53467. }
  53468. return false;
  53469. },
  53470. enumerable: true,
  53471. configurable: true
  53472. });
  53473. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53474. /**
  53475. * Does exist one action manager with at least one pick trigger
  53476. **/
  53477. get: function () {
  53478. for (var t in ActionManager.Triggers) {
  53479. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53480. var t_int = parseInt(t);
  53481. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53482. return true;
  53483. }
  53484. }
  53485. }
  53486. return false;
  53487. },
  53488. enumerable: true,
  53489. configurable: true
  53490. });
  53491. /**
  53492. * Does exist one action manager that handles actions of a given trigger
  53493. * @param trigger defines the trigger to be tested
  53494. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53495. **/
  53496. ActionManager.HasSpecificTrigger = function (trigger) {
  53497. for (var t in ActionManager.Triggers) {
  53498. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53499. var t_int = parseInt(t);
  53500. if (t_int === trigger) {
  53501. return true;
  53502. }
  53503. }
  53504. }
  53505. return false;
  53506. };
  53507. /**
  53508. * Registers an action to this action manager
  53509. * @param action defines the action to be registered
  53510. * @return the action amended (prepared) after registration
  53511. */
  53512. ActionManager.prototype.registerAction = function (action) {
  53513. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53514. if (this.getScene().actionManager !== this) {
  53515. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53516. return null;
  53517. }
  53518. }
  53519. this.actions.push(action);
  53520. if (ActionManager.Triggers[action.trigger]) {
  53521. ActionManager.Triggers[action.trigger]++;
  53522. }
  53523. else {
  53524. ActionManager.Triggers[action.trigger] = 1;
  53525. }
  53526. action._actionManager = this;
  53527. action._prepare();
  53528. return action;
  53529. };
  53530. /**
  53531. * Unregisters an action to this action manager
  53532. * @param action defines the action to be unregistered
  53533. * @return a boolean indicating whether the action has been unregistered
  53534. */
  53535. ActionManager.prototype.unregisterAction = function (action) {
  53536. var index = this.actions.indexOf(action);
  53537. if (index !== -1) {
  53538. this.actions.splice(index, 1);
  53539. ActionManager.Triggers[action.trigger] -= 1;
  53540. if (ActionManager.Triggers[action.trigger] === 0) {
  53541. delete ActionManager.Triggers[action.trigger];
  53542. }
  53543. delete action._actionManager;
  53544. return true;
  53545. }
  53546. return false;
  53547. };
  53548. /**
  53549. * Process a specific trigger
  53550. * @param trigger defines the trigger to process
  53551. * @param evt defines the event details to be processed
  53552. */
  53553. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53554. for (var index = 0; index < this.actions.length; index++) {
  53555. var action = this.actions[index];
  53556. if (action.trigger === trigger) {
  53557. if (evt) {
  53558. if (trigger === ActionManager.OnKeyUpTrigger
  53559. || trigger === ActionManager.OnKeyDownTrigger) {
  53560. var parameter = action.getTriggerParameter();
  53561. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53562. if (!parameter.toLowerCase) {
  53563. continue;
  53564. }
  53565. var lowerCase = parameter.toLowerCase();
  53566. if (lowerCase !== evt.sourceEvent.key) {
  53567. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53568. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53569. if (actualkey !== lowerCase) {
  53570. continue;
  53571. }
  53572. }
  53573. }
  53574. }
  53575. }
  53576. action._executeCurrent(evt);
  53577. }
  53578. }
  53579. };
  53580. /** @hidden */
  53581. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53582. var properties = propertyPath.split(".");
  53583. for (var index = 0; index < properties.length - 1; index++) {
  53584. target = target[properties[index]];
  53585. }
  53586. return target;
  53587. };
  53588. /** @hidden */
  53589. ActionManager.prototype._getProperty = function (propertyPath) {
  53590. var properties = propertyPath.split(".");
  53591. return properties[properties.length - 1];
  53592. };
  53593. /**
  53594. * Serialize this manager to a JSON object
  53595. * @param name defines the property name to store this manager
  53596. * @returns a JSON representation of this manager
  53597. */
  53598. ActionManager.prototype.serialize = function (name) {
  53599. var root = {
  53600. children: new Array(),
  53601. name: name,
  53602. type: 3,
  53603. properties: new Array() // Empty for root but required
  53604. };
  53605. for (var i = 0; i < this.actions.length; i++) {
  53606. var triggerObject = {
  53607. type: 0,
  53608. children: new Array(),
  53609. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53610. properties: new Array()
  53611. };
  53612. var triggerOptions = this.actions[i].triggerOptions;
  53613. if (triggerOptions && typeof triggerOptions !== "number") {
  53614. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53615. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53616. }
  53617. else {
  53618. var parameter = {};
  53619. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53620. if (triggerOptions.parameter.mesh) {
  53621. parameter._meshId = triggerOptions.parameter.mesh.id;
  53622. }
  53623. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53624. }
  53625. }
  53626. // Serialize child action, recursively
  53627. this.actions[i].serialize(triggerObject);
  53628. // Add serialized trigger
  53629. root.children.push(triggerObject);
  53630. }
  53631. return root;
  53632. };
  53633. /**
  53634. * Creates a new ActionManager from a JSON data
  53635. * @param parsedActions defines the JSON data to read from
  53636. * @param object defines the hosting mesh
  53637. * @param scene defines the hosting scene
  53638. */
  53639. ActionManager.Parse = function (parsedActions, object, scene) {
  53640. var actionManager = new ActionManager(scene);
  53641. if (object === null)
  53642. scene.actionManager = actionManager;
  53643. else
  53644. object.actionManager = actionManager;
  53645. // instanciate a new object
  53646. var instanciate = function (name, params) {
  53647. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53648. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53649. newInstance.constructor.apply(newInstance, params);
  53650. return newInstance;
  53651. };
  53652. var parseParameter = function (name, value, target, propertyPath) {
  53653. if (propertyPath === null) {
  53654. // String, boolean or float
  53655. var floatValue = parseFloat(value);
  53656. if (value === "true" || value === "false")
  53657. return value === "true";
  53658. else
  53659. return isNaN(floatValue) ? value : floatValue;
  53660. }
  53661. var effectiveTarget = propertyPath.split(".");
  53662. var values = value.split(",");
  53663. // Get effective Target
  53664. for (var i = 0; i < effectiveTarget.length; i++) {
  53665. target = target[effectiveTarget[i]];
  53666. }
  53667. // Return appropriate value with its type
  53668. if (typeof (target) === "boolean")
  53669. return values[0] === "true";
  53670. if (typeof (target) === "string")
  53671. return values[0];
  53672. // Parameters with multiple values such as Vector3 etc.
  53673. var split = new Array();
  53674. for (var i = 0; i < values.length; i++)
  53675. split.push(parseFloat(values[i]));
  53676. if (target instanceof BABYLON.Vector3)
  53677. return BABYLON.Vector3.FromArray(split);
  53678. if (target instanceof BABYLON.Vector4)
  53679. return BABYLON.Vector4.FromArray(split);
  53680. if (target instanceof BABYLON.Color3)
  53681. return BABYLON.Color3.FromArray(split);
  53682. if (target instanceof BABYLON.Color4)
  53683. return BABYLON.Color4.FromArray(split);
  53684. return parseFloat(values[0]);
  53685. };
  53686. // traverse graph per trigger
  53687. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53688. if (combineArray === void 0) { combineArray = null; }
  53689. if (parsedAction.detached)
  53690. return;
  53691. var parameters = new Array();
  53692. var target = null;
  53693. var propertyPath = null;
  53694. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53695. // Parameters
  53696. if (parsedAction.type === 2)
  53697. parameters.push(actionManager);
  53698. else
  53699. parameters.push(trigger);
  53700. if (combine) {
  53701. var actions = new Array();
  53702. for (var j = 0; j < parsedAction.combine.length; j++) {
  53703. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53704. }
  53705. parameters.push(actions);
  53706. }
  53707. else {
  53708. for (var i = 0; i < parsedAction.properties.length; i++) {
  53709. var value = parsedAction.properties[i].value;
  53710. var name = parsedAction.properties[i].name;
  53711. var targetType = parsedAction.properties[i].targetType;
  53712. if (name === "target")
  53713. if (targetType !== null && targetType === "SceneProperties")
  53714. value = target = scene;
  53715. else
  53716. value = target = scene.getNodeByName(value);
  53717. else if (name === "parent")
  53718. value = scene.getNodeByName(value);
  53719. else if (name === "sound")
  53720. value = scene.getSoundByName(value);
  53721. else if (name !== "propertyPath") {
  53722. if (parsedAction.type === 2 && name === "operator")
  53723. value = BABYLON.ValueCondition[value];
  53724. else
  53725. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53726. }
  53727. else {
  53728. propertyPath = value;
  53729. }
  53730. parameters.push(value);
  53731. }
  53732. }
  53733. if (combineArray === null) {
  53734. parameters.push(condition);
  53735. }
  53736. else {
  53737. parameters.push(null);
  53738. }
  53739. // If interpolate value action
  53740. if (parsedAction.name === "InterpolateValueAction") {
  53741. var param = parameters[parameters.length - 2];
  53742. parameters[parameters.length - 1] = param;
  53743. parameters[parameters.length - 2] = condition;
  53744. }
  53745. // Action or condition(s) and not CombineAction
  53746. var newAction = instanciate(parsedAction.name, parameters);
  53747. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53748. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53749. if (action)
  53750. action.then(nothing);
  53751. else
  53752. actionManager.registerAction(nothing);
  53753. action = nothing;
  53754. }
  53755. if (combineArray === null) {
  53756. if (newAction instanceof BABYLON.Condition) {
  53757. condition = newAction;
  53758. newAction = action;
  53759. }
  53760. else {
  53761. condition = null;
  53762. if (action)
  53763. action.then(newAction);
  53764. else
  53765. actionManager.registerAction(newAction);
  53766. }
  53767. }
  53768. else {
  53769. combineArray.push(newAction);
  53770. }
  53771. for (var i = 0; i < parsedAction.children.length; i++)
  53772. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53773. };
  53774. // triggers
  53775. for (var i = 0; i < parsedActions.children.length; i++) {
  53776. var triggerParams;
  53777. var trigger = parsedActions.children[i];
  53778. if (trigger.properties.length > 0) {
  53779. var param = trigger.properties[0].value;
  53780. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53781. if (value._meshId) {
  53782. value.mesh = scene.getMeshByID(value._meshId);
  53783. }
  53784. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53785. }
  53786. else
  53787. triggerParams = ActionManager[trigger.name];
  53788. for (var j = 0; j < trigger.children.length; j++) {
  53789. if (!trigger.detached)
  53790. traverse(trigger.children[j], triggerParams, null, null);
  53791. }
  53792. }
  53793. };
  53794. /**
  53795. * Get a trigger name by index
  53796. * @param trigger defines the trigger index
  53797. * @returns a trigger name
  53798. */
  53799. ActionManager.GetTriggerName = function (trigger) {
  53800. switch (trigger) {
  53801. case 0: return "NothingTrigger";
  53802. case 1: return "OnPickTrigger";
  53803. case 2: return "OnLeftPickTrigger";
  53804. case 3: return "OnRightPickTrigger";
  53805. case 4: return "OnCenterPickTrigger";
  53806. case 5: return "OnPickDownTrigger";
  53807. case 6: return "OnPickUpTrigger";
  53808. case 7: return "OnLongPressTrigger";
  53809. case 8: return "OnPointerOverTrigger";
  53810. case 9: return "OnPointerOutTrigger";
  53811. case 10: return "OnEveryFrameTrigger";
  53812. case 11: return "OnIntersectionEnterTrigger";
  53813. case 12: return "OnIntersectionExitTrigger";
  53814. case 13: return "OnKeyDownTrigger";
  53815. case 14: return "OnKeyUpTrigger";
  53816. case 15: return "OnPickOutTrigger";
  53817. default: return "";
  53818. }
  53819. };
  53820. // Statics
  53821. ActionManager._NothingTrigger = 0;
  53822. ActionManager._OnPickTrigger = 1;
  53823. ActionManager._OnLeftPickTrigger = 2;
  53824. ActionManager._OnRightPickTrigger = 3;
  53825. ActionManager._OnCenterPickTrigger = 4;
  53826. ActionManager._OnPickDownTrigger = 5;
  53827. ActionManager._OnDoublePickTrigger = 6;
  53828. ActionManager._OnPickUpTrigger = 7;
  53829. ActionManager._OnLongPressTrigger = 8;
  53830. ActionManager._OnPointerOverTrigger = 9;
  53831. ActionManager._OnPointerOutTrigger = 10;
  53832. ActionManager._OnEveryFrameTrigger = 11;
  53833. ActionManager._OnIntersectionEnterTrigger = 12;
  53834. ActionManager._OnIntersectionExitTrigger = 13;
  53835. ActionManager._OnKeyDownTrigger = 14;
  53836. ActionManager._OnKeyUpTrigger = 15;
  53837. ActionManager._OnPickOutTrigger = 16;
  53838. /** Gets the list of active triggers */
  53839. ActionManager.Triggers = {};
  53840. return ActionManager;
  53841. }());
  53842. BABYLON.ActionManager = ActionManager;
  53843. })(BABYLON || (BABYLON = {}));
  53844. //# sourceMappingURL=babylon.actionManager.js.map
  53845. var BABYLON;
  53846. (function (BABYLON) {
  53847. var InterpolateValueAction = /** @class */ (function (_super) {
  53848. __extends(InterpolateValueAction, _super);
  53849. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53850. if (duration === void 0) { duration = 1000; }
  53851. var _this = _super.call(this, triggerOptions, condition) || this;
  53852. _this.propertyPath = propertyPath;
  53853. _this.value = value;
  53854. _this.duration = duration;
  53855. _this.stopOtherAnimations = stopOtherAnimations;
  53856. _this.onInterpolationDone = onInterpolationDone;
  53857. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53858. _this._target = _this._effectiveTarget = target;
  53859. return _this;
  53860. }
  53861. InterpolateValueAction.prototype._prepare = function () {
  53862. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53863. this._property = this._getProperty(this.propertyPath);
  53864. };
  53865. InterpolateValueAction.prototype.execute = function () {
  53866. var _this = this;
  53867. var scene = this._actionManager.getScene();
  53868. var keys = [
  53869. {
  53870. frame: 0,
  53871. value: this._effectiveTarget[this._property]
  53872. }, {
  53873. frame: 100,
  53874. value: this.value
  53875. }
  53876. ];
  53877. var dataType;
  53878. if (typeof this.value === "number") {
  53879. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53880. }
  53881. else if (this.value instanceof BABYLON.Color3) {
  53882. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53883. }
  53884. else if (this.value instanceof BABYLON.Vector3) {
  53885. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53886. }
  53887. else if (this.value instanceof BABYLON.Matrix) {
  53888. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53889. }
  53890. else if (this.value instanceof BABYLON.Quaternion) {
  53891. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53892. }
  53893. else {
  53894. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53895. return;
  53896. }
  53897. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53898. animation.setKeys(keys);
  53899. if (this.stopOtherAnimations) {
  53900. scene.stopAnimation(this._effectiveTarget);
  53901. }
  53902. var wrapper = function () {
  53903. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53904. if (_this.onInterpolationDone) {
  53905. _this.onInterpolationDone();
  53906. }
  53907. };
  53908. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53909. };
  53910. InterpolateValueAction.prototype.serialize = function (parent) {
  53911. return _super.prototype._serialize.call(this, {
  53912. name: "InterpolateValueAction",
  53913. properties: [
  53914. BABYLON.Action._GetTargetProperty(this._target),
  53915. { name: "propertyPath", value: this.propertyPath },
  53916. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53917. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53918. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53919. ]
  53920. }, parent);
  53921. };
  53922. return InterpolateValueAction;
  53923. }(BABYLON.Action));
  53924. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53925. })(BABYLON || (BABYLON = {}));
  53926. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53927. var BABYLON;
  53928. (function (BABYLON) {
  53929. var SwitchBooleanAction = /** @class */ (function (_super) {
  53930. __extends(SwitchBooleanAction, _super);
  53931. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53932. var _this = _super.call(this, triggerOptions, condition) || this;
  53933. _this.propertyPath = propertyPath;
  53934. _this._target = _this._effectiveTarget = target;
  53935. return _this;
  53936. }
  53937. SwitchBooleanAction.prototype._prepare = function () {
  53938. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53939. this._property = this._getProperty(this.propertyPath);
  53940. };
  53941. SwitchBooleanAction.prototype.execute = function () {
  53942. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53943. };
  53944. SwitchBooleanAction.prototype.serialize = function (parent) {
  53945. return _super.prototype._serialize.call(this, {
  53946. name: "SwitchBooleanAction",
  53947. properties: [
  53948. BABYLON.Action._GetTargetProperty(this._target),
  53949. { name: "propertyPath", value: this.propertyPath }
  53950. ]
  53951. }, parent);
  53952. };
  53953. return SwitchBooleanAction;
  53954. }(BABYLON.Action));
  53955. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53956. var SetStateAction = /** @class */ (function (_super) {
  53957. __extends(SetStateAction, _super);
  53958. function SetStateAction(triggerOptions, target, value, condition) {
  53959. var _this = _super.call(this, triggerOptions, condition) || this;
  53960. _this.value = value;
  53961. _this._target = target;
  53962. return _this;
  53963. }
  53964. SetStateAction.prototype.execute = function () {
  53965. this._target.state = this.value;
  53966. };
  53967. SetStateAction.prototype.serialize = function (parent) {
  53968. return _super.prototype._serialize.call(this, {
  53969. name: "SetStateAction",
  53970. properties: [
  53971. BABYLON.Action._GetTargetProperty(this._target),
  53972. { name: "value", value: this.value }
  53973. ]
  53974. }, parent);
  53975. };
  53976. return SetStateAction;
  53977. }(BABYLON.Action));
  53978. BABYLON.SetStateAction = SetStateAction;
  53979. var SetValueAction = /** @class */ (function (_super) {
  53980. __extends(SetValueAction, _super);
  53981. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53982. var _this = _super.call(this, triggerOptions, condition) || this;
  53983. _this.propertyPath = propertyPath;
  53984. _this.value = value;
  53985. _this._target = _this._effectiveTarget = target;
  53986. return _this;
  53987. }
  53988. SetValueAction.prototype._prepare = function () {
  53989. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53990. this._property = this._getProperty(this.propertyPath);
  53991. };
  53992. SetValueAction.prototype.execute = function () {
  53993. this._effectiveTarget[this._property] = this.value;
  53994. if (this._target.markAsDirty) {
  53995. this._target.markAsDirty(this._property);
  53996. }
  53997. };
  53998. SetValueAction.prototype.serialize = function (parent) {
  53999. return _super.prototype._serialize.call(this, {
  54000. name: "SetValueAction",
  54001. properties: [
  54002. BABYLON.Action._GetTargetProperty(this._target),
  54003. { name: "propertyPath", value: this.propertyPath },
  54004. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54005. ]
  54006. }, parent);
  54007. };
  54008. return SetValueAction;
  54009. }(BABYLON.Action));
  54010. BABYLON.SetValueAction = SetValueAction;
  54011. var IncrementValueAction = /** @class */ (function (_super) {
  54012. __extends(IncrementValueAction, _super);
  54013. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54014. var _this = _super.call(this, triggerOptions, condition) || this;
  54015. _this.propertyPath = propertyPath;
  54016. _this.value = value;
  54017. _this._target = _this._effectiveTarget = target;
  54018. return _this;
  54019. }
  54020. IncrementValueAction.prototype._prepare = function () {
  54021. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54022. this._property = this._getProperty(this.propertyPath);
  54023. if (typeof this._effectiveTarget[this._property] !== "number") {
  54024. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54025. }
  54026. };
  54027. IncrementValueAction.prototype.execute = function () {
  54028. this._effectiveTarget[this._property] += this.value;
  54029. if (this._target.markAsDirty) {
  54030. this._target.markAsDirty(this._property);
  54031. }
  54032. };
  54033. IncrementValueAction.prototype.serialize = function (parent) {
  54034. return _super.prototype._serialize.call(this, {
  54035. name: "IncrementValueAction",
  54036. properties: [
  54037. BABYLON.Action._GetTargetProperty(this._target),
  54038. { name: "propertyPath", value: this.propertyPath },
  54039. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54040. ]
  54041. }, parent);
  54042. };
  54043. return IncrementValueAction;
  54044. }(BABYLON.Action));
  54045. BABYLON.IncrementValueAction = IncrementValueAction;
  54046. var PlayAnimationAction = /** @class */ (function (_super) {
  54047. __extends(PlayAnimationAction, _super);
  54048. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54049. var _this = _super.call(this, triggerOptions, condition) || this;
  54050. _this.from = from;
  54051. _this.to = to;
  54052. _this.loop = loop;
  54053. _this._target = target;
  54054. return _this;
  54055. }
  54056. PlayAnimationAction.prototype._prepare = function () {
  54057. };
  54058. PlayAnimationAction.prototype.execute = function () {
  54059. var scene = this._actionManager.getScene();
  54060. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54061. };
  54062. PlayAnimationAction.prototype.serialize = function (parent) {
  54063. return _super.prototype._serialize.call(this, {
  54064. name: "PlayAnimationAction",
  54065. properties: [
  54066. BABYLON.Action._GetTargetProperty(this._target),
  54067. { name: "from", value: String(this.from) },
  54068. { name: "to", value: String(this.to) },
  54069. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54070. ]
  54071. }, parent);
  54072. };
  54073. return PlayAnimationAction;
  54074. }(BABYLON.Action));
  54075. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54076. var StopAnimationAction = /** @class */ (function (_super) {
  54077. __extends(StopAnimationAction, _super);
  54078. function StopAnimationAction(triggerOptions, target, condition) {
  54079. var _this = _super.call(this, triggerOptions, condition) || this;
  54080. _this._target = target;
  54081. return _this;
  54082. }
  54083. StopAnimationAction.prototype._prepare = function () {
  54084. };
  54085. StopAnimationAction.prototype.execute = function () {
  54086. var scene = this._actionManager.getScene();
  54087. scene.stopAnimation(this._target);
  54088. };
  54089. StopAnimationAction.prototype.serialize = function (parent) {
  54090. return _super.prototype._serialize.call(this, {
  54091. name: "StopAnimationAction",
  54092. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54093. }, parent);
  54094. };
  54095. return StopAnimationAction;
  54096. }(BABYLON.Action));
  54097. BABYLON.StopAnimationAction = StopAnimationAction;
  54098. var DoNothingAction = /** @class */ (function (_super) {
  54099. __extends(DoNothingAction, _super);
  54100. function DoNothingAction(triggerOptions, condition) {
  54101. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54102. return _super.call(this, triggerOptions, condition) || this;
  54103. }
  54104. DoNothingAction.prototype.execute = function () {
  54105. };
  54106. DoNothingAction.prototype.serialize = function (parent) {
  54107. return _super.prototype._serialize.call(this, {
  54108. name: "DoNothingAction",
  54109. properties: []
  54110. }, parent);
  54111. };
  54112. return DoNothingAction;
  54113. }(BABYLON.Action));
  54114. BABYLON.DoNothingAction = DoNothingAction;
  54115. var CombineAction = /** @class */ (function (_super) {
  54116. __extends(CombineAction, _super);
  54117. function CombineAction(triggerOptions, children, condition) {
  54118. var _this = _super.call(this, triggerOptions, condition) || this;
  54119. _this.children = children;
  54120. return _this;
  54121. }
  54122. CombineAction.prototype._prepare = function () {
  54123. for (var index = 0; index < this.children.length; index++) {
  54124. this.children[index]._actionManager = this._actionManager;
  54125. this.children[index]._prepare();
  54126. }
  54127. };
  54128. CombineAction.prototype.execute = function (evt) {
  54129. for (var index = 0; index < this.children.length; index++) {
  54130. this.children[index].execute(evt);
  54131. }
  54132. };
  54133. CombineAction.prototype.serialize = function (parent) {
  54134. var serializationObject = _super.prototype._serialize.call(this, {
  54135. name: "CombineAction",
  54136. properties: [],
  54137. combine: []
  54138. }, parent);
  54139. for (var i = 0; i < this.children.length; i++) {
  54140. serializationObject.combine.push(this.children[i].serialize(null));
  54141. }
  54142. return serializationObject;
  54143. };
  54144. return CombineAction;
  54145. }(BABYLON.Action));
  54146. BABYLON.CombineAction = CombineAction;
  54147. var ExecuteCodeAction = /** @class */ (function (_super) {
  54148. __extends(ExecuteCodeAction, _super);
  54149. function ExecuteCodeAction(triggerOptions, func, condition) {
  54150. var _this = _super.call(this, triggerOptions, condition) || this;
  54151. _this.func = func;
  54152. return _this;
  54153. }
  54154. ExecuteCodeAction.prototype.execute = function (evt) {
  54155. this.func(evt);
  54156. };
  54157. return ExecuteCodeAction;
  54158. }(BABYLON.Action));
  54159. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54160. var SetParentAction = /** @class */ (function (_super) {
  54161. __extends(SetParentAction, _super);
  54162. function SetParentAction(triggerOptions, target, parent, condition) {
  54163. var _this = _super.call(this, triggerOptions, condition) || this;
  54164. _this._target = target;
  54165. _this._parent = parent;
  54166. return _this;
  54167. }
  54168. SetParentAction.prototype._prepare = function () {
  54169. };
  54170. SetParentAction.prototype.execute = function () {
  54171. if (this._target.parent === this._parent) {
  54172. return;
  54173. }
  54174. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54175. invertParentWorldMatrix.invert();
  54176. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54177. this._target.parent = this._parent;
  54178. };
  54179. SetParentAction.prototype.serialize = function (parent) {
  54180. return _super.prototype._serialize.call(this, {
  54181. name: "SetParentAction",
  54182. properties: [
  54183. BABYLON.Action._GetTargetProperty(this._target),
  54184. BABYLON.Action._GetTargetProperty(this._parent),
  54185. ]
  54186. }, parent);
  54187. };
  54188. return SetParentAction;
  54189. }(BABYLON.Action));
  54190. BABYLON.SetParentAction = SetParentAction;
  54191. var PlaySoundAction = /** @class */ (function (_super) {
  54192. __extends(PlaySoundAction, _super);
  54193. function PlaySoundAction(triggerOptions, sound, condition) {
  54194. var _this = _super.call(this, triggerOptions, condition) || this;
  54195. _this._sound = sound;
  54196. return _this;
  54197. }
  54198. PlaySoundAction.prototype._prepare = function () {
  54199. };
  54200. PlaySoundAction.prototype.execute = function () {
  54201. if (this._sound !== undefined)
  54202. this._sound.play();
  54203. };
  54204. PlaySoundAction.prototype.serialize = function (parent) {
  54205. return _super.prototype._serialize.call(this, {
  54206. name: "PlaySoundAction",
  54207. properties: [{ name: "sound", value: this._sound.name }]
  54208. }, parent);
  54209. };
  54210. return PlaySoundAction;
  54211. }(BABYLON.Action));
  54212. BABYLON.PlaySoundAction = PlaySoundAction;
  54213. var StopSoundAction = /** @class */ (function (_super) {
  54214. __extends(StopSoundAction, _super);
  54215. function StopSoundAction(triggerOptions, sound, condition) {
  54216. var _this = _super.call(this, triggerOptions, condition) || this;
  54217. _this._sound = sound;
  54218. return _this;
  54219. }
  54220. StopSoundAction.prototype._prepare = function () {
  54221. };
  54222. StopSoundAction.prototype.execute = function () {
  54223. if (this._sound !== undefined)
  54224. this._sound.stop();
  54225. };
  54226. StopSoundAction.prototype.serialize = function (parent) {
  54227. return _super.prototype._serialize.call(this, {
  54228. name: "StopSoundAction",
  54229. properties: [{ name: "sound", value: this._sound.name }]
  54230. }, parent);
  54231. };
  54232. return StopSoundAction;
  54233. }(BABYLON.Action));
  54234. BABYLON.StopSoundAction = StopSoundAction;
  54235. })(BABYLON || (BABYLON = {}));
  54236. //# sourceMappingURL=babylon.directActions.js.map
  54237. var BABYLON;
  54238. (function (BABYLON) {
  54239. var SpriteManager = /** @class */ (function () {
  54240. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54241. if (epsilon === void 0) { epsilon = 0.01; }
  54242. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54243. this.name = name;
  54244. this.sprites = new Array();
  54245. this.renderingGroupId = 0;
  54246. this.layerMask = 0x0FFFFFFF;
  54247. this.fogEnabled = true;
  54248. this.isPickable = false;
  54249. /**
  54250. * An event triggered when the manager is disposed.
  54251. */
  54252. this.onDisposeObservable = new BABYLON.Observable();
  54253. this._vertexBuffers = {};
  54254. this._capacity = capacity;
  54255. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54256. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54257. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54258. if (cellSize.width && cellSize.height) {
  54259. this.cellWidth = cellSize.width;
  54260. this.cellHeight = cellSize.height;
  54261. }
  54262. else if (cellSize !== undefined) {
  54263. this.cellWidth = cellSize;
  54264. this.cellHeight = cellSize;
  54265. }
  54266. else {
  54267. return;
  54268. }
  54269. this._epsilon = epsilon;
  54270. this._scene = scene;
  54271. this._scene.spriteManagers.push(this);
  54272. var indices = [];
  54273. var index = 0;
  54274. for (var count = 0; count < capacity; count++) {
  54275. indices.push(index);
  54276. indices.push(index + 1);
  54277. indices.push(index + 2);
  54278. indices.push(index);
  54279. indices.push(index + 2);
  54280. indices.push(index + 3);
  54281. index += 4;
  54282. }
  54283. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54284. // VBO
  54285. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54286. this._vertexData = new Float32Array(capacity * 16 * 4);
  54287. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54288. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54289. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54290. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54291. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54292. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54293. this._vertexBuffers["options"] = options;
  54294. this._vertexBuffers["cellInfo"] = cellInfo;
  54295. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54296. // Effects
  54297. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54298. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54299. }
  54300. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54301. set: function (callback) {
  54302. if (this._onDisposeObserver) {
  54303. this.onDisposeObservable.remove(this._onDisposeObserver);
  54304. }
  54305. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54306. },
  54307. enumerable: true,
  54308. configurable: true
  54309. });
  54310. Object.defineProperty(SpriteManager.prototype, "texture", {
  54311. get: function () {
  54312. return this._spriteTexture;
  54313. },
  54314. set: function (value) {
  54315. this._spriteTexture = value;
  54316. },
  54317. enumerable: true,
  54318. configurable: true
  54319. });
  54320. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54321. var arrayOffset = index * 16;
  54322. if (offsetX === 0)
  54323. offsetX = this._epsilon;
  54324. else if (offsetX === 1)
  54325. offsetX = 1 - this._epsilon;
  54326. if (offsetY === 0)
  54327. offsetY = this._epsilon;
  54328. else if (offsetY === 1)
  54329. offsetY = 1 - this._epsilon;
  54330. this._vertexData[arrayOffset] = sprite.position.x;
  54331. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54332. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54333. this._vertexData[arrayOffset + 3] = sprite.angle;
  54334. this._vertexData[arrayOffset + 4] = sprite.width;
  54335. this._vertexData[arrayOffset + 5] = sprite.height;
  54336. this._vertexData[arrayOffset + 6] = offsetX;
  54337. this._vertexData[arrayOffset + 7] = offsetY;
  54338. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54339. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54340. var offset = (sprite.cellIndex / rowSize) >> 0;
  54341. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54342. this._vertexData[arrayOffset + 11] = offset;
  54343. // Color
  54344. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54345. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54346. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54347. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54348. };
  54349. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54350. var count = Math.min(this._capacity, this.sprites.length);
  54351. var min = BABYLON.Vector3.Zero();
  54352. var max = BABYLON.Vector3.Zero();
  54353. var distance = Number.MAX_VALUE;
  54354. var currentSprite = null;
  54355. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54356. var cameraView = camera.getViewMatrix();
  54357. for (var index = 0; index < count; index++) {
  54358. var sprite = this.sprites[index];
  54359. if (!sprite) {
  54360. continue;
  54361. }
  54362. if (predicate) {
  54363. if (!predicate(sprite)) {
  54364. continue;
  54365. }
  54366. }
  54367. else if (!sprite.isPickable) {
  54368. continue;
  54369. }
  54370. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54371. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54372. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54373. if (ray.intersectsBoxMinMax(min, max)) {
  54374. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54375. if (distance > currentDistance) {
  54376. distance = currentDistance;
  54377. currentSprite = sprite;
  54378. if (fastCheck) {
  54379. break;
  54380. }
  54381. }
  54382. }
  54383. }
  54384. if (currentSprite) {
  54385. var result = new BABYLON.PickingInfo();
  54386. result.hit = true;
  54387. result.pickedSprite = currentSprite;
  54388. result.distance = distance;
  54389. return result;
  54390. }
  54391. return null;
  54392. };
  54393. SpriteManager.prototype.render = function () {
  54394. // Check
  54395. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54396. return;
  54397. var engine = this._scene.getEngine();
  54398. var baseSize = this._spriteTexture.getBaseSize();
  54399. // Sprites
  54400. var deltaTime = engine.getDeltaTime();
  54401. var max = Math.min(this._capacity, this.sprites.length);
  54402. var rowSize = baseSize.width / this.cellWidth;
  54403. var offset = 0;
  54404. for (var index = 0; index < max; index++) {
  54405. var sprite = this.sprites[index];
  54406. if (!sprite) {
  54407. continue;
  54408. }
  54409. sprite._animate(deltaTime);
  54410. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54411. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54412. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54413. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54414. }
  54415. this._buffer.update(this._vertexData);
  54416. // Render
  54417. var effect = this._effectBase;
  54418. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54419. effect = this._effectFog;
  54420. }
  54421. engine.enableEffect(effect);
  54422. var viewMatrix = this._scene.getViewMatrix();
  54423. effect.setTexture("diffuseSampler", this._spriteTexture);
  54424. effect.setMatrix("view", viewMatrix);
  54425. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54426. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54427. // Fog
  54428. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54429. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54430. effect.setColor3("vFogColor", this._scene.fogColor);
  54431. }
  54432. // VBOs
  54433. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54434. // Draw order
  54435. engine.setDepthFunctionToLessOrEqual();
  54436. effect.setBool("alphaTest", true);
  54437. engine.setColorWrite(false);
  54438. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54439. engine.setColorWrite(true);
  54440. effect.setBool("alphaTest", false);
  54441. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54442. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54443. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54444. };
  54445. SpriteManager.prototype.dispose = function () {
  54446. if (this._buffer) {
  54447. this._buffer.dispose();
  54448. this._buffer = null;
  54449. }
  54450. if (this._indexBuffer) {
  54451. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54452. this._indexBuffer = null;
  54453. }
  54454. if (this._spriteTexture) {
  54455. this._spriteTexture.dispose();
  54456. this._spriteTexture = null;
  54457. }
  54458. // Remove from scene
  54459. var index = this._scene.spriteManagers.indexOf(this);
  54460. this._scene.spriteManagers.splice(index, 1);
  54461. // Callback
  54462. this.onDisposeObservable.notifyObservers(this);
  54463. this.onDisposeObservable.clear();
  54464. };
  54465. return SpriteManager;
  54466. }());
  54467. BABYLON.SpriteManager = SpriteManager;
  54468. })(BABYLON || (BABYLON = {}));
  54469. //# sourceMappingURL=babylon.spriteManager.js.map
  54470. var BABYLON;
  54471. (function (BABYLON) {
  54472. var Sprite = /** @class */ (function () {
  54473. function Sprite(name, manager) {
  54474. this.name = name;
  54475. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54476. this.width = 1.0;
  54477. this.height = 1.0;
  54478. this.angle = 0;
  54479. this.cellIndex = 0;
  54480. this.invertU = 0;
  54481. this.invertV = 0;
  54482. this.animations = new Array();
  54483. this.isPickable = false;
  54484. this._animationStarted = false;
  54485. this._loopAnimation = false;
  54486. this._fromIndex = 0;
  54487. this._toIndex = 0;
  54488. this._delay = 0;
  54489. this._direction = 1;
  54490. this._time = 0;
  54491. this._manager = manager;
  54492. this._manager.sprites.push(this);
  54493. this.position = BABYLON.Vector3.Zero();
  54494. }
  54495. Object.defineProperty(Sprite.prototype, "size", {
  54496. get: function () {
  54497. return this.width;
  54498. },
  54499. set: function (value) {
  54500. this.width = value;
  54501. this.height = value;
  54502. },
  54503. enumerable: true,
  54504. configurable: true
  54505. });
  54506. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54507. this._fromIndex = from;
  54508. this._toIndex = to;
  54509. this._loopAnimation = loop;
  54510. this._delay = delay;
  54511. this._animationStarted = true;
  54512. this._direction = from < to ? 1 : -1;
  54513. this.cellIndex = from;
  54514. this._time = 0;
  54515. this._onAnimationEnd = onAnimationEnd;
  54516. };
  54517. Sprite.prototype.stopAnimation = function () {
  54518. this._animationStarted = false;
  54519. };
  54520. Sprite.prototype._animate = function (deltaTime) {
  54521. if (!this._animationStarted)
  54522. return;
  54523. this._time += deltaTime;
  54524. if (this._time > this._delay) {
  54525. this._time = this._time % this._delay;
  54526. this.cellIndex += this._direction;
  54527. if (this.cellIndex > this._toIndex) {
  54528. if (this._loopAnimation) {
  54529. this.cellIndex = this._fromIndex;
  54530. }
  54531. else {
  54532. this.cellIndex = this._toIndex;
  54533. this._animationStarted = false;
  54534. if (this._onAnimationEnd) {
  54535. this._onAnimationEnd();
  54536. }
  54537. if (this.disposeWhenFinishedAnimating) {
  54538. this.dispose();
  54539. }
  54540. }
  54541. }
  54542. }
  54543. };
  54544. Sprite.prototype.dispose = function () {
  54545. for (var i = 0; i < this._manager.sprites.length; i++) {
  54546. if (this._manager.sprites[i] == this) {
  54547. this._manager.sprites.splice(i, 1);
  54548. }
  54549. }
  54550. };
  54551. return Sprite;
  54552. }());
  54553. BABYLON.Sprite = Sprite;
  54554. })(BABYLON || (BABYLON = {}));
  54555. //# sourceMappingURL=babylon.sprite.js.map
  54556. var BABYLON;
  54557. (function (BABYLON) {
  54558. var IntersectionInfo = /** @class */ (function () {
  54559. function IntersectionInfo(bu, bv, distance) {
  54560. this.bu = bu;
  54561. this.bv = bv;
  54562. this.distance = distance;
  54563. this.faceId = 0;
  54564. this.subMeshId = 0;
  54565. }
  54566. return IntersectionInfo;
  54567. }());
  54568. BABYLON.IntersectionInfo = IntersectionInfo;
  54569. var PickingInfo = /** @class */ (function () {
  54570. function PickingInfo() {
  54571. this.hit = false;
  54572. this.distance = 0;
  54573. this.pickedPoint = null;
  54574. this.pickedMesh = null;
  54575. this.bu = 0;
  54576. this.bv = 0;
  54577. this.faceId = -1;
  54578. this.subMeshId = 0;
  54579. this.pickedSprite = null;
  54580. }
  54581. // Methods
  54582. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54583. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54584. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54585. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54586. return null;
  54587. }
  54588. var indices = this.pickedMesh.getIndices();
  54589. if (!indices) {
  54590. return null;
  54591. }
  54592. var result;
  54593. if (useVerticesNormals) {
  54594. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54595. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54596. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54597. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54598. normal0 = normal0.scale(this.bu);
  54599. normal1 = normal1.scale(this.bv);
  54600. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54601. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54602. }
  54603. else {
  54604. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54605. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54606. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54607. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54608. var p1p2 = vertex1.subtract(vertex2);
  54609. var p3p2 = vertex3.subtract(vertex2);
  54610. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54611. }
  54612. if (useWorldCoordinates) {
  54613. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54614. }
  54615. return BABYLON.Vector3.Normalize(result);
  54616. };
  54617. PickingInfo.prototype.getTextureCoordinates = function () {
  54618. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54619. return null;
  54620. }
  54621. var indices = this.pickedMesh.getIndices();
  54622. if (!indices) {
  54623. return null;
  54624. }
  54625. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54626. if (!uvs) {
  54627. return null;
  54628. }
  54629. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54630. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54631. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54632. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54633. uv1 = uv1.scale(this.bu);
  54634. uv2 = uv2.scale(this.bv);
  54635. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54636. };
  54637. return PickingInfo;
  54638. }());
  54639. BABYLON.PickingInfo = PickingInfo;
  54640. })(BABYLON || (BABYLON = {}));
  54641. //# sourceMappingURL=babylon.pickingInfo.js.map
  54642. var BABYLON;
  54643. (function (BABYLON) {
  54644. var Ray = /** @class */ (function () {
  54645. function Ray(origin, direction, length) {
  54646. if (length === void 0) { length = Number.MAX_VALUE; }
  54647. this.origin = origin;
  54648. this.direction = direction;
  54649. this.length = length;
  54650. }
  54651. // Methods
  54652. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54653. var d = 0.0;
  54654. var maxValue = Number.MAX_VALUE;
  54655. var inv;
  54656. var min;
  54657. var max;
  54658. var temp;
  54659. if (Math.abs(this.direction.x) < 0.0000001) {
  54660. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54661. return false;
  54662. }
  54663. }
  54664. else {
  54665. inv = 1.0 / this.direction.x;
  54666. min = (minimum.x - this.origin.x) * inv;
  54667. max = (maximum.x - this.origin.x) * inv;
  54668. if (max === -Infinity) {
  54669. max = Infinity;
  54670. }
  54671. if (min > max) {
  54672. temp = min;
  54673. min = max;
  54674. max = temp;
  54675. }
  54676. d = Math.max(min, d);
  54677. maxValue = Math.min(max, maxValue);
  54678. if (d > maxValue) {
  54679. return false;
  54680. }
  54681. }
  54682. if (Math.abs(this.direction.y) < 0.0000001) {
  54683. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54684. return false;
  54685. }
  54686. }
  54687. else {
  54688. inv = 1.0 / this.direction.y;
  54689. min = (minimum.y - this.origin.y) * inv;
  54690. max = (maximum.y - this.origin.y) * inv;
  54691. if (max === -Infinity) {
  54692. max = Infinity;
  54693. }
  54694. if (min > max) {
  54695. temp = min;
  54696. min = max;
  54697. max = temp;
  54698. }
  54699. d = Math.max(min, d);
  54700. maxValue = Math.min(max, maxValue);
  54701. if (d > maxValue) {
  54702. return false;
  54703. }
  54704. }
  54705. if (Math.abs(this.direction.z) < 0.0000001) {
  54706. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54707. return false;
  54708. }
  54709. }
  54710. else {
  54711. inv = 1.0 / this.direction.z;
  54712. min = (minimum.z - this.origin.z) * inv;
  54713. max = (maximum.z - this.origin.z) * inv;
  54714. if (max === -Infinity) {
  54715. max = Infinity;
  54716. }
  54717. if (min > max) {
  54718. temp = min;
  54719. min = max;
  54720. max = temp;
  54721. }
  54722. d = Math.max(min, d);
  54723. maxValue = Math.min(max, maxValue);
  54724. if (d > maxValue) {
  54725. return false;
  54726. }
  54727. }
  54728. return true;
  54729. };
  54730. Ray.prototype.intersectsBox = function (box) {
  54731. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54732. };
  54733. Ray.prototype.intersectsSphere = function (sphere) {
  54734. var x = sphere.center.x - this.origin.x;
  54735. var y = sphere.center.y - this.origin.y;
  54736. var z = sphere.center.z - this.origin.z;
  54737. var pyth = (x * x) + (y * y) + (z * z);
  54738. var rr = sphere.radius * sphere.radius;
  54739. if (pyth <= rr) {
  54740. return true;
  54741. }
  54742. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54743. if (dot < 0.0) {
  54744. return false;
  54745. }
  54746. var temp = pyth - (dot * dot);
  54747. return temp <= rr;
  54748. };
  54749. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54750. if (!this._edge1) {
  54751. this._edge1 = BABYLON.Vector3.Zero();
  54752. this._edge2 = BABYLON.Vector3.Zero();
  54753. this._pvec = BABYLON.Vector3.Zero();
  54754. this._tvec = BABYLON.Vector3.Zero();
  54755. this._qvec = BABYLON.Vector3.Zero();
  54756. }
  54757. vertex1.subtractToRef(vertex0, this._edge1);
  54758. vertex2.subtractToRef(vertex0, this._edge2);
  54759. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54760. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54761. if (det === 0) {
  54762. return null;
  54763. }
  54764. var invdet = 1 / det;
  54765. this.origin.subtractToRef(vertex0, this._tvec);
  54766. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54767. if (bu < 0 || bu > 1.0) {
  54768. return null;
  54769. }
  54770. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54771. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54772. if (bv < 0 || bu + bv > 1.0) {
  54773. return null;
  54774. }
  54775. //check if the distance is longer than the predefined length.
  54776. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54777. if (distance > this.length) {
  54778. return null;
  54779. }
  54780. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54781. };
  54782. Ray.prototype.intersectsPlane = function (plane) {
  54783. var distance;
  54784. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54785. if (Math.abs(result1) < 9.99999997475243E-07) {
  54786. return null;
  54787. }
  54788. else {
  54789. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54790. distance = (-plane.d - result2) / result1;
  54791. if (distance < 0.0) {
  54792. if (distance < -9.99999997475243E-07) {
  54793. return null;
  54794. }
  54795. else {
  54796. return 0;
  54797. }
  54798. }
  54799. return distance;
  54800. }
  54801. };
  54802. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54803. var tm = BABYLON.Tmp.Matrix[0];
  54804. mesh.getWorldMatrix().invertToRef(tm);
  54805. if (this._tmpRay) {
  54806. Ray.TransformToRef(this, tm, this._tmpRay);
  54807. }
  54808. else {
  54809. this._tmpRay = Ray.Transform(this, tm);
  54810. }
  54811. return mesh.intersects(this._tmpRay, fastCheck);
  54812. };
  54813. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54814. if (results) {
  54815. results.length = 0;
  54816. }
  54817. else {
  54818. results = [];
  54819. }
  54820. for (var i = 0; i < meshes.length; i++) {
  54821. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54822. if (pickInfo.hit) {
  54823. results.push(pickInfo);
  54824. }
  54825. }
  54826. results.sort(this._comparePickingInfo);
  54827. return results;
  54828. };
  54829. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54830. if (pickingInfoA.distance < pickingInfoB.distance) {
  54831. return -1;
  54832. }
  54833. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54834. return 1;
  54835. }
  54836. else {
  54837. return 0;
  54838. }
  54839. };
  54840. /**
  54841. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54842. * @param sega the first point of the segment to test the intersection against
  54843. * @param segb the second point of the segment to test the intersection against
  54844. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54845. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54846. */
  54847. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54848. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54849. var u = segb.subtract(sega);
  54850. var v = rsegb.subtract(this.origin);
  54851. var w = sega.subtract(this.origin);
  54852. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54853. var b = BABYLON.Vector3.Dot(u, v);
  54854. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54855. var d = BABYLON.Vector3.Dot(u, w);
  54856. var e = BABYLON.Vector3.Dot(v, w);
  54857. var D = a * c - b * b; // always >= 0
  54858. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54859. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54860. // compute the line parameters of the two closest points
  54861. if (D < Ray.smallnum) { // the lines are almost parallel
  54862. sN = 0.0; // force using point P0 on segment S1
  54863. sD = 1.0; // to prevent possible division by 0.0 later
  54864. tN = e;
  54865. tD = c;
  54866. }
  54867. else { // get the closest points on the infinite lines
  54868. sN = (b * e - c * d);
  54869. tN = (a * e - b * d);
  54870. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54871. sN = 0.0;
  54872. tN = e;
  54873. tD = c;
  54874. }
  54875. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54876. sN = sD;
  54877. tN = e + b;
  54878. tD = c;
  54879. }
  54880. }
  54881. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54882. tN = 0.0;
  54883. // recompute sc for this edge
  54884. if (-d < 0.0) {
  54885. sN = 0.0;
  54886. }
  54887. else if (-d > a)
  54888. sN = sD;
  54889. else {
  54890. sN = -d;
  54891. sD = a;
  54892. }
  54893. }
  54894. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54895. tN = tD;
  54896. // recompute sc for this edge
  54897. if ((-d + b) < 0.0) {
  54898. sN = 0;
  54899. }
  54900. else if ((-d + b) > a) {
  54901. sN = sD;
  54902. }
  54903. else {
  54904. sN = (-d + b);
  54905. sD = a;
  54906. }
  54907. }
  54908. // finally do the division to get sc and tc
  54909. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54910. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54911. // get the difference of the two closest points
  54912. var qtc = v.multiplyByFloats(tc, tc, tc);
  54913. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54914. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54915. if (isIntersected) {
  54916. return qtc.length();
  54917. }
  54918. return -1;
  54919. };
  54920. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54921. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54922. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54923. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54924. this.direction.normalize();
  54925. return this;
  54926. };
  54927. // Statics
  54928. Ray.Zero = function () {
  54929. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54930. };
  54931. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54932. var result = Ray.Zero();
  54933. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54934. };
  54935. /**
  54936. * 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
  54937. * transformed to the given world matrix.
  54938. * @param origin The origin point
  54939. * @param end The end point
  54940. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54941. */
  54942. Ray.CreateNewFromTo = function (origin, end, world) {
  54943. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54944. var direction = end.subtract(origin);
  54945. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54946. direction.normalize();
  54947. return Ray.Transform(new Ray(origin, direction, length), world);
  54948. };
  54949. Ray.Transform = function (ray, matrix) {
  54950. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54951. Ray.TransformToRef(ray, matrix, result);
  54952. return result;
  54953. };
  54954. Ray.TransformToRef = function (ray, matrix, result) {
  54955. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54956. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54957. result.length = ray.length;
  54958. var dir = result.direction;
  54959. var len = dir.length();
  54960. if (!(len === 0 || len === 1)) {
  54961. var num = 1.0 / len;
  54962. dir.x *= num;
  54963. dir.y *= num;
  54964. dir.z *= num;
  54965. result.length *= len;
  54966. }
  54967. };
  54968. Ray.smallnum = 0.00000001;
  54969. Ray.rayl = 10e8;
  54970. return Ray;
  54971. }());
  54972. BABYLON.Ray = Ray;
  54973. })(BABYLON || (BABYLON = {}));
  54974. //# sourceMappingURL=babylon.ray.js.map
  54975. var BABYLON;
  54976. (function (BABYLON) {
  54977. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54978. if (boxMin.x > sphereCenter.x + sphereRadius)
  54979. return false;
  54980. if (sphereCenter.x - sphereRadius > boxMax.x)
  54981. return false;
  54982. if (boxMin.y > sphereCenter.y + sphereRadius)
  54983. return false;
  54984. if (sphereCenter.y - sphereRadius > boxMax.y)
  54985. return false;
  54986. if (boxMin.z > sphereCenter.z + sphereRadius)
  54987. return false;
  54988. if (sphereCenter.z - sphereRadius > boxMax.z)
  54989. return false;
  54990. return true;
  54991. };
  54992. var getLowestRoot = (function () {
  54993. var result = { root: 0, found: false };
  54994. return function (a, b, c, maxR) {
  54995. result.root = 0;
  54996. result.found = false;
  54997. var determinant = b * b - 4.0 * a * c;
  54998. if (determinant < 0)
  54999. return result;
  55000. var sqrtD = Math.sqrt(determinant);
  55001. var r1 = (-b - sqrtD) / (2.0 * a);
  55002. var r2 = (-b + sqrtD) / (2.0 * a);
  55003. if (r1 > r2) {
  55004. var temp = r2;
  55005. r2 = r1;
  55006. r1 = temp;
  55007. }
  55008. if (r1 > 0 && r1 < maxR) {
  55009. result.root = r1;
  55010. result.found = true;
  55011. return result;
  55012. }
  55013. if (r2 > 0 && r2 < maxR) {
  55014. result.root = r2;
  55015. result.found = true;
  55016. return result;
  55017. }
  55018. return result;
  55019. };
  55020. })();
  55021. var Collider = /** @class */ (function () {
  55022. function Collider() {
  55023. this._collisionPoint = BABYLON.Vector3.Zero();
  55024. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55025. this._tempVector = BABYLON.Vector3.Zero();
  55026. this._tempVector2 = BABYLON.Vector3.Zero();
  55027. this._tempVector3 = BABYLON.Vector3.Zero();
  55028. this._tempVector4 = BABYLON.Vector3.Zero();
  55029. this._edge = BABYLON.Vector3.Zero();
  55030. this._baseToVertex = BABYLON.Vector3.Zero();
  55031. this._destinationPoint = BABYLON.Vector3.Zero();
  55032. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55033. this._displacementVector = BABYLON.Vector3.Zero();
  55034. this._radius = BABYLON.Vector3.One();
  55035. this._retry = 0;
  55036. this._basePointWorld = BABYLON.Vector3.Zero();
  55037. this._velocityWorld = BABYLON.Vector3.Zero();
  55038. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55039. this._collisionMask = -1;
  55040. }
  55041. Object.defineProperty(Collider.prototype, "collisionMask", {
  55042. get: function () {
  55043. return this._collisionMask;
  55044. },
  55045. set: function (mask) {
  55046. this._collisionMask = !isNaN(mask) ? mask : -1;
  55047. },
  55048. enumerable: true,
  55049. configurable: true
  55050. });
  55051. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55052. /**
  55053. * Gets the plane normal used to compute the sliding response (in local space)
  55054. */
  55055. get: function () {
  55056. return this._slidePlaneNormal;
  55057. },
  55058. enumerable: true,
  55059. configurable: true
  55060. });
  55061. // Methods
  55062. Collider.prototype._initialize = function (source, dir, e) {
  55063. this._velocity = dir;
  55064. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55065. this._basePoint = source;
  55066. source.multiplyToRef(this._radius, this._basePointWorld);
  55067. dir.multiplyToRef(this._radius, this._velocityWorld);
  55068. this._velocityWorldLength = this._velocityWorld.length();
  55069. this._epsilon = e;
  55070. this.collisionFound = false;
  55071. };
  55072. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55073. pa.subtractToRef(point, this._tempVector);
  55074. pb.subtractToRef(point, this._tempVector2);
  55075. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55076. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55077. if (d < 0)
  55078. return false;
  55079. pc.subtractToRef(point, this._tempVector3);
  55080. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55081. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55082. if (d < 0)
  55083. return false;
  55084. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55085. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55086. return d >= 0;
  55087. };
  55088. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55089. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55090. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55091. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55092. return false;
  55093. }
  55094. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55095. return false;
  55096. return true;
  55097. };
  55098. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55099. var t0;
  55100. var embeddedInPlane = false;
  55101. //defensive programming, actually not needed.
  55102. if (!trianglePlaneArray) {
  55103. trianglePlaneArray = [];
  55104. }
  55105. if (!trianglePlaneArray[faceIndex]) {
  55106. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55107. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55108. }
  55109. var trianglePlane = trianglePlaneArray[faceIndex];
  55110. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55111. return;
  55112. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55113. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55114. if (normalDotVelocity == 0) {
  55115. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55116. return;
  55117. embeddedInPlane = true;
  55118. t0 = 0;
  55119. }
  55120. else {
  55121. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55122. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55123. if (t0 > t1) {
  55124. var temp = t1;
  55125. t1 = t0;
  55126. t0 = temp;
  55127. }
  55128. if (t0 > 1.0 || t1 < 0.0)
  55129. return;
  55130. if (t0 < 0)
  55131. t0 = 0;
  55132. if (t0 > 1.0)
  55133. t0 = 1.0;
  55134. }
  55135. this._collisionPoint.copyFromFloats(0, 0, 0);
  55136. var found = false;
  55137. var t = 1.0;
  55138. if (!embeddedInPlane) {
  55139. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55140. this._velocity.scaleToRef(t0, this._tempVector);
  55141. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55142. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55143. found = true;
  55144. t = t0;
  55145. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55146. }
  55147. }
  55148. if (!found) {
  55149. var velocitySquaredLength = this._velocity.lengthSquared();
  55150. var a = velocitySquaredLength;
  55151. this._basePoint.subtractToRef(p1, this._tempVector);
  55152. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55153. var c = this._tempVector.lengthSquared() - 1.0;
  55154. var lowestRoot = getLowestRoot(a, b, c, t);
  55155. if (lowestRoot.found) {
  55156. t = lowestRoot.root;
  55157. found = true;
  55158. this._collisionPoint.copyFrom(p1);
  55159. }
  55160. this._basePoint.subtractToRef(p2, this._tempVector);
  55161. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55162. c = this._tempVector.lengthSquared() - 1.0;
  55163. lowestRoot = getLowestRoot(a, b, c, t);
  55164. if (lowestRoot.found) {
  55165. t = lowestRoot.root;
  55166. found = true;
  55167. this._collisionPoint.copyFrom(p2);
  55168. }
  55169. this._basePoint.subtractToRef(p3, this._tempVector);
  55170. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55171. c = this._tempVector.lengthSquared() - 1.0;
  55172. lowestRoot = getLowestRoot(a, b, c, t);
  55173. if (lowestRoot.found) {
  55174. t = lowestRoot.root;
  55175. found = true;
  55176. this._collisionPoint.copyFrom(p3);
  55177. }
  55178. p2.subtractToRef(p1, this._edge);
  55179. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55180. var edgeSquaredLength = this._edge.lengthSquared();
  55181. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55182. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55183. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55184. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55185. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55186. lowestRoot = getLowestRoot(a, b, c, t);
  55187. if (lowestRoot.found) {
  55188. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55189. if (f >= 0.0 && f <= 1.0) {
  55190. t = lowestRoot.root;
  55191. found = true;
  55192. this._edge.scaleInPlace(f);
  55193. p1.addToRef(this._edge, this._collisionPoint);
  55194. }
  55195. }
  55196. p3.subtractToRef(p2, this._edge);
  55197. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55198. edgeSquaredLength = this._edge.lengthSquared();
  55199. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55200. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55201. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55202. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55203. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55204. lowestRoot = getLowestRoot(a, b, c, t);
  55205. if (lowestRoot.found) {
  55206. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55207. if (f >= 0.0 && f <= 1.0) {
  55208. t = lowestRoot.root;
  55209. found = true;
  55210. this._edge.scaleInPlace(f);
  55211. p2.addToRef(this._edge, this._collisionPoint);
  55212. }
  55213. }
  55214. p1.subtractToRef(p3, this._edge);
  55215. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55216. edgeSquaredLength = this._edge.lengthSquared();
  55217. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55218. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55219. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55220. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55221. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55222. lowestRoot = getLowestRoot(a, b, c, t);
  55223. if (lowestRoot.found) {
  55224. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55225. if (f >= 0.0 && f <= 1.0) {
  55226. t = lowestRoot.root;
  55227. found = true;
  55228. this._edge.scaleInPlace(f);
  55229. p3.addToRef(this._edge, this._collisionPoint);
  55230. }
  55231. }
  55232. }
  55233. if (found) {
  55234. var distToCollision = t * this._velocity.length();
  55235. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55236. if (!this.intersectionPoint) {
  55237. this.intersectionPoint = this._collisionPoint.clone();
  55238. }
  55239. else {
  55240. this.intersectionPoint.copyFrom(this._collisionPoint);
  55241. }
  55242. this._nearestDistance = distToCollision;
  55243. this.collisionFound = true;
  55244. }
  55245. }
  55246. };
  55247. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55248. for (var i = indexStart; i < indexEnd; i += 3) {
  55249. var p1 = pts[indices[i] - decal];
  55250. var p2 = pts[indices[i + 1] - decal];
  55251. var p3 = pts[indices[i + 2] - decal];
  55252. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55253. }
  55254. };
  55255. Collider.prototype._getResponse = function (pos, vel) {
  55256. pos.addToRef(vel, this._destinationPoint);
  55257. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55258. this._basePoint.addToRef(vel, pos);
  55259. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55260. this._slidePlaneNormal.normalize();
  55261. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55262. pos.addInPlace(this._displacementVector);
  55263. this.intersectionPoint.addInPlace(this._displacementVector);
  55264. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55265. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55266. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55267. };
  55268. return Collider;
  55269. }());
  55270. BABYLON.Collider = Collider;
  55271. })(BABYLON || (BABYLON = {}));
  55272. //# sourceMappingURL=babylon.collider.js.map
  55273. var BABYLON;
  55274. (function (BABYLON) {
  55275. //WebWorker code will be inserted to this variable.
  55276. BABYLON.CollisionWorker = "";
  55277. /** Defines supported task for worker process */
  55278. var WorkerTaskType;
  55279. (function (WorkerTaskType) {
  55280. /** Initialization */
  55281. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55282. /** Update of geometry */
  55283. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55284. /** Evaluate collision */
  55285. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55286. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55287. /** Defines kind of replies returned by worker */
  55288. var WorkerReplyType;
  55289. (function (WorkerReplyType) {
  55290. /** Success */
  55291. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55292. /** Unkown error */
  55293. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55294. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55295. var CollisionCoordinatorWorker = /** @class */ (function () {
  55296. function CollisionCoordinatorWorker() {
  55297. var _this = this;
  55298. this._scaledPosition = BABYLON.Vector3.Zero();
  55299. this._scaledVelocity = BABYLON.Vector3.Zero();
  55300. this.onMeshUpdated = function (transformNode) {
  55301. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55302. };
  55303. this.onGeometryUpdated = function (geometry) {
  55304. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55305. };
  55306. this._afterRender = function () {
  55307. if (!_this._init)
  55308. return;
  55309. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55310. return;
  55311. }
  55312. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55313. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55314. if (_this._runningUpdated > 4) {
  55315. return;
  55316. }
  55317. ++_this._runningUpdated;
  55318. var payload = {
  55319. updatedMeshes: _this._addUpdateMeshesList,
  55320. updatedGeometries: _this._addUpdateGeometriesList,
  55321. removedGeometries: _this._toRemoveGeometryArray,
  55322. removedMeshes: _this._toRemoveMeshesArray
  55323. };
  55324. var message = {
  55325. payload: payload,
  55326. taskType: WorkerTaskType.UPDATE
  55327. };
  55328. var serializable = [];
  55329. for (var id in payload.updatedGeometries) {
  55330. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55331. //prepare transferables
  55332. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55333. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55334. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55335. }
  55336. }
  55337. _this._worker.postMessage(message, serializable);
  55338. _this._addUpdateMeshesList = {};
  55339. _this._addUpdateGeometriesList = {};
  55340. _this._toRemoveGeometryArray = [];
  55341. _this._toRemoveMeshesArray = [];
  55342. };
  55343. this._onMessageFromWorker = function (e) {
  55344. var returnData = e.data;
  55345. if (returnData.error != WorkerReplyType.SUCCESS) {
  55346. //TODO what errors can be returned from the worker?
  55347. BABYLON.Tools.Warn("error returned from worker!");
  55348. return;
  55349. }
  55350. switch (returnData.taskType) {
  55351. case WorkerTaskType.INIT:
  55352. _this._init = true;
  55353. //Update the worked with ALL of the scene's current state
  55354. _this._scene.meshes.forEach(function (mesh) {
  55355. _this.onMeshAdded(mesh);
  55356. });
  55357. _this._scene.getGeometries().forEach(function (geometry) {
  55358. _this.onGeometryAdded(geometry);
  55359. });
  55360. break;
  55361. case WorkerTaskType.UPDATE:
  55362. _this._runningUpdated--;
  55363. break;
  55364. case WorkerTaskType.COLLIDE:
  55365. var returnPayload = returnData.payload;
  55366. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55367. return;
  55368. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55369. if (callback) {
  55370. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55371. if (mesh) {
  55372. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55373. }
  55374. }
  55375. //cleanup
  55376. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55377. break;
  55378. }
  55379. };
  55380. this._collisionsCallbackArray = [];
  55381. this._init = false;
  55382. this._runningUpdated = 0;
  55383. this._addUpdateMeshesList = {};
  55384. this._addUpdateGeometriesList = {};
  55385. this._toRemoveGeometryArray = [];
  55386. this._toRemoveMeshesArray = [];
  55387. }
  55388. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55389. if (!this._init)
  55390. return;
  55391. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55392. return;
  55393. position.divideToRef(collider._radius, this._scaledPosition);
  55394. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55395. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55396. var payload = {
  55397. collider: {
  55398. position: this._scaledPosition.asArray(),
  55399. velocity: this._scaledVelocity.asArray(),
  55400. radius: collider._radius.asArray()
  55401. },
  55402. collisionId: collisionIndex,
  55403. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55404. maximumRetry: maximumRetry
  55405. };
  55406. var message = {
  55407. payload: payload,
  55408. taskType: WorkerTaskType.COLLIDE
  55409. };
  55410. this._worker.postMessage(message);
  55411. };
  55412. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55413. this._scene = scene;
  55414. this._scene.registerAfterRender(this._afterRender);
  55415. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55416. this._worker = new Worker(workerUrl);
  55417. this._worker.onmessage = this._onMessageFromWorker;
  55418. var message = {
  55419. payload: {},
  55420. taskType: WorkerTaskType.INIT
  55421. };
  55422. this._worker.postMessage(message);
  55423. };
  55424. CollisionCoordinatorWorker.prototype.destroy = function () {
  55425. this._scene.unregisterAfterRender(this._afterRender);
  55426. this._worker.terminate();
  55427. };
  55428. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55429. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55430. this.onMeshUpdated(mesh);
  55431. };
  55432. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55433. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55434. };
  55435. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55436. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55437. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55438. this.onGeometryUpdated(geometry);
  55439. };
  55440. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55441. this._toRemoveGeometryArray.push(geometry.id);
  55442. };
  55443. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55444. var submeshes = [];
  55445. if (mesh.subMeshes) {
  55446. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55447. var boundingInfo = sm.getBoundingInfo();
  55448. return {
  55449. position: idx,
  55450. verticesStart: sm.verticesStart,
  55451. verticesCount: sm.verticesCount,
  55452. indexStart: sm.indexStart,
  55453. indexCount: sm.indexCount,
  55454. hasMaterial: !!sm.getMaterial(),
  55455. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55456. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55457. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55458. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55459. };
  55460. });
  55461. }
  55462. var geometryId = null;
  55463. if (mesh instanceof BABYLON.Mesh) {
  55464. var geometry = mesh.geometry;
  55465. geometryId = geometry ? geometry.id : null;
  55466. }
  55467. else if (mesh instanceof BABYLON.InstancedMesh) {
  55468. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55469. geometryId = geometry ? geometry.id : null;
  55470. }
  55471. var boundingInfo = mesh.getBoundingInfo();
  55472. return {
  55473. uniqueId: mesh.uniqueId,
  55474. id: mesh.id,
  55475. name: mesh.name,
  55476. geometryId: geometryId,
  55477. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55478. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55479. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55480. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55481. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55482. subMeshes: submeshes,
  55483. checkCollisions: mesh.checkCollisions
  55484. };
  55485. };
  55486. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55487. return {
  55488. id: geometry.id,
  55489. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55490. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55491. indices: new Uint32Array(geometry.getIndices() || []),
  55492. };
  55493. };
  55494. return CollisionCoordinatorWorker;
  55495. }());
  55496. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55497. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55498. function CollisionCoordinatorLegacy() {
  55499. this._scaledPosition = BABYLON.Vector3.Zero();
  55500. this._scaledVelocity = BABYLON.Vector3.Zero();
  55501. this._finalPosition = BABYLON.Vector3.Zero();
  55502. }
  55503. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55504. position.divideToRef(collider._radius, this._scaledPosition);
  55505. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55506. collider.collidedMesh = null;
  55507. collider._retry = 0;
  55508. collider._initialVelocity = this._scaledVelocity;
  55509. collider._initialPosition = this._scaledPosition;
  55510. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55511. this._finalPosition.multiplyInPlace(collider._radius);
  55512. //run the callback
  55513. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55514. };
  55515. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55516. this._scene = scene;
  55517. };
  55518. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55519. //Legacy need no destruction method.
  55520. };
  55521. //No update in legacy mode
  55522. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55523. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55524. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55525. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55526. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55527. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55528. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55529. if (excludedMesh === void 0) { excludedMesh = null; }
  55530. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55531. if (collider._retry >= maximumRetry) {
  55532. finalPosition.copyFrom(position);
  55533. return;
  55534. }
  55535. // Check if this is a mesh else camera or -1
  55536. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55537. collider._initialize(position, velocity, closeDistance);
  55538. // Check all meshes
  55539. for (var index = 0; index < this._scene.meshes.length; index++) {
  55540. var mesh = this._scene.meshes[index];
  55541. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55542. mesh._checkCollision(collider);
  55543. }
  55544. }
  55545. if (!collider.collisionFound) {
  55546. position.addToRef(velocity, finalPosition);
  55547. return;
  55548. }
  55549. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55550. collider._getResponse(position, velocity);
  55551. }
  55552. if (velocity.length() <= closeDistance) {
  55553. finalPosition.copyFrom(position);
  55554. return;
  55555. }
  55556. collider._retry++;
  55557. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55558. };
  55559. return CollisionCoordinatorLegacy;
  55560. }());
  55561. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55562. })(BABYLON || (BABYLON = {}));
  55563. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55564. var BABYLON;
  55565. (function (BABYLON) {
  55566. /**
  55567. * A particle represents one of the element emitted by a particle system.
  55568. * This is mainly define by its coordinates, direction, velocity and age.
  55569. */
  55570. var Particle = /** @class */ (function () {
  55571. /**
  55572. * Creates a new instance Particle
  55573. * @param particleSystem the particle system the particle belongs to
  55574. */
  55575. function Particle(
  55576. /**
  55577. * particleSystem the particle system the particle belongs to.
  55578. */
  55579. particleSystem) {
  55580. this.particleSystem = particleSystem;
  55581. /**
  55582. * The world position of the particle in the scene.
  55583. */
  55584. this.position = BABYLON.Vector3.Zero();
  55585. /**
  55586. * The world direction of the particle in the scene.
  55587. */
  55588. this.direction = BABYLON.Vector3.Zero();
  55589. /**
  55590. * The color of the particle.
  55591. */
  55592. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55593. /**
  55594. * The color change of the particle per step.
  55595. */
  55596. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55597. /**
  55598. * Defines how long will the life of the particle be.
  55599. */
  55600. this.lifeTime = 1.0;
  55601. /**
  55602. * The current age of the particle.
  55603. */
  55604. this.age = 0;
  55605. /**
  55606. * The current size of the particle.
  55607. */
  55608. this.size = 0;
  55609. /**
  55610. * The current angle of the particle.
  55611. */
  55612. this.angle = 0;
  55613. /**
  55614. * Defines how fast is the angle changing.
  55615. */
  55616. this.angularSpeed = 0;
  55617. /**
  55618. * Defines the cell index used by the particle to be rendered from a sprite.
  55619. */
  55620. this.cellIndex = 0;
  55621. this._currentFrameCounter = 0;
  55622. if (!this.particleSystem.isAnimationSheetEnabled) {
  55623. return;
  55624. }
  55625. this.updateCellInfoFromSystem();
  55626. }
  55627. Particle.prototype.updateCellInfoFromSystem = function () {
  55628. this.cellIndex = this.particleSystem.startSpriteCellID;
  55629. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55630. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55631. }
  55632. else {
  55633. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55634. }
  55635. };
  55636. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55637. // (ageOffset / scaledUpdateSpeed) / available cells
  55638. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55639. this._currentFrameCounter += scaledUpdateSpeed;
  55640. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55641. this._currentFrameCounter = 0;
  55642. this.cellIndex++;
  55643. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55644. this.cellIndex = this.particleSystem.endSpriteCellID;
  55645. }
  55646. }
  55647. };
  55648. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55649. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55650. this.cellIndex++;
  55651. this._currentFrameCounter = 0;
  55652. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55653. if (this.particleSystem.spriteCellLoop) {
  55654. this.cellIndex = this.particleSystem.startSpriteCellID;
  55655. }
  55656. else {
  55657. this.cellIndex = this.particleSystem.endSpriteCellID;
  55658. }
  55659. }
  55660. }
  55661. else {
  55662. this._currentFrameCounter++;
  55663. }
  55664. };
  55665. /**
  55666. * Copy the properties of particle to another one.
  55667. * @param other the particle to copy the information to.
  55668. */
  55669. Particle.prototype.copyTo = function (other) {
  55670. other.position.copyFrom(this.position);
  55671. other.direction.copyFrom(this.direction);
  55672. other.color.copyFrom(this.color);
  55673. other.colorStep.copyFrom(this.colorStep);
  55674. other.lifeTime = this.lifeTime;
  55675. other.age = this.age;
  55676. other.size = this.size;
  55677. other.angle = this.angle;
  55678. other.angularSpeed = this.angularSpeed;
  55679. other.particleSystem = this.particleSystem;
  55680. other.cellIndex = this.cellIndex;
  55681. };
  55682. return Particle;
  55683. }());
  55684. BABYLON.Particle = Particle;
  55685. })(BABYLON || (BABYLON = {}));
  55686. //# sourceMappingURL=babylon.particle.js.map
  55687. var BABYLON;
  55688. (function (BABYLON) {
  55689. /**
  55690. * This represents a particle system in Babylon.
  55691. * 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.
  55692. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55693. * @example https://doc.babylonjs.com/babylon101/particles
  55694. */
  55695. var ParticleSystem = /** @class */ (function () {
  55696. /**
  55697. * Instantiates a particle system.
  55698. * 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.
  55699. * @param name The name of the particle system
  55700. * @param capacity The max number of particles alive at the same time
  55701. * @param scene The scene the particle system belongs to
  55702. * @param customEffect a custom effect used to change the way particles are rendered by default
  55703. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55704. * @param epsilon Offset used to render the particles
  55705. */
  55706. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55707. if (customEffect === void 0) { customEffect = null; }
  55708. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55709. if (epsilon === void 0) { epsilon = 0.01; }
  55710. var _this = this;
  55711. /**
  55712. * List of animations used by the particle system.
  55713. */
  55714. this.animations = [];
  55715. /**
  55716. * The rendering group used by the Particle system to chose when to render.
  55717. */
  55718. this.renderingGroupId = 0;
  55719. /**
  55720. * The emitter represents the Mesh or position we are attaching the particle system to.
  55721. */
  55722. this.emitter = null;
  55723. /**
  55724. * The maximum number of particles to emit per frame
  55725. */
  55726. this.emitRate = 10;
  55727. /**
  55728. * If you want to launch only a few particles at once, that can be done, as well.
  55729. */
  55730. this.manualEmitCount = -1;
  55731. /**
  55732. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55733. */
  55734. this.updateSpeed = 0.01;
  55735. /**
  55736. * The amount of time the particle system is running (depends of the overall update speed).
  55737. */
  55738. this.targetStopDuration = 0;
  55739. /**
  55740. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55741. */
  55742. this.disposeOnStop = false;
  55743. /**
  55744. * Minimum power of emitting particles.
  55745. */
  55746. this.minEmitPower = 1;
  55747. /**
  55748. * Maximum power of emitting particles.
  55749. */
  55750. this.maxEmitPower = 1;
  55751. /**
  55752. * Minimum life time of emitting particles.
  55753. */
  55754. this.minLifeTime = 1;
  55755. /**
  55756. * Maximum life time of emitting particles.
  55757. */
  55758. this.maxLifeTime = 1;
  55759. /**
  55760. * Minimum Size of emitting particles.
  55761. */
  55762. this.minSize = 1;
  55763. /**
  55764. * Maximum Size of emitting particles.
  55765. */
  55766. this.maxSize = 1;
  55767. /**
  55768. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55769. */
  55770. this.minAngularSpeed = 0;
  55771. /**
  55772. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55773. */
  55774. this.maxAngularSpeed = 0;
  55775. /**
  55776. * The layer mask we are rendering the particles through.
  55777. */
  55778. this.layerMask = 0x0FFFFFFF;
  55779. /**
  55780. * This can help using your own shader to render the particle system.
  55781. * The according effect will be created
  55782. */
  55783. this.customShader = null;
  55784. /**
  55785. * By default particle system starts as soon as they are created. This prevents the
  55786. * automatic start to happen and let you decide when to start emitting particles.
  55787. */
  55788. this.preventAutoStart = false;
  55789. /**
  55790. * Callback triggered when the particle animation is ending.
  55791. */
  55792. this.onAnimationEnd = null;
  55793. /**
  55794. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55795. */
  55796. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55797. /**
  55798. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55799. * to override the particles.
  55800. */
  55801. this.forceDepthWrite = false;
  55802. /**
  55803. * You can use gravity if you want to give an orientation to your particles.
  55804. */
  55805. this.gravity = BABYLON.Vector3.Zero();
  55806. /**
  55807. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55808. */
  55809. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55810. /**
  55811. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55812. */
  55813. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55814. /**
  55815. * Color the particle will have at the end of its lifetime.
  55816. */
  55817. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55818. /**
  55819. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55820. */
  55821. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55822. /**
  55823. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55824. */
  55825. this.spriteCellLoop = true;
  55826. /**
  55827. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55828. */
  55829. this.spriteCellChangeSpeed = 0;
  55830. /**
  55831. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55832. */
  55833. this.startSpriteCellID = 0;
  55834. /**
  55835. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55836. */
  55837. this.endSpriteCellID = 0;
  55838. /**
  55839. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55840. */
  55841. this.spriteCellWidth = 0;
  55842. /**
  55843. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55844. */
  55845. this.spriteCellHeight = 0;
  55846. /**
  55847. * An event triggered when the system is disposed.
  55848. */
  55849. this.onDisposeObservable = new BABYLON.Observable();
  55850. this._particles = new Array();
  55851. this._stockParticles = new Array();
  55852. this._newPartsExcess = 0;
  55853. this._vertexBuffers = {};
  55854. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55855. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55856. this._scaledDirection = BABYLON.Vector3.Zero();
  55857. this._scaledGravity = BABYLON.Vector3.Zero();
  55858. this._currentRenderId = -1;
  55859. this._started = false;
  55860. this._stopped = false;
  55861. this._actualFrame = 0;
  55862. this._vertexBufferSize = 11;
  55863. // start of sub system methods
  55864. /**
  55865. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55866. * Its lifetime will start back at 0.
  55867. */
  55868. this.recycleParticle = function (particle) {
  55869. var lastParticle = _this._particles.pop();
  55870. if (lastParticle !== particle) {
  55871. lastParticle.copyTo(particle);
  55872. }
  55873. _this._stockParticles.push(lastParticle);
  55874. };
  55875. this._createParticle = function () {
  55876. var particle;
  55877. if (_this._stockParticles.length !== 0) {
  55878. particle = _this._stockParticles.pop();
  55879. particle.age = 0;
  55880. particle.cellIndex = _this.startSpriteCellID;
  55881. }
  55882. else {
  55883. particle = new BABYLON.Particle(_this);
  55884. }
  55885. return particle;
  55886. };
  55887. this._emitFromParticle = function (particle) {
  55888. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55889. return;
  55890. }
  55891. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55892. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55893. subSystem._rootParticleSystem = _this;
  55894. _this.activeSubSystems.push(subSystem);
  55895. subSystem.start();
  55896. };
  55897. this._appendParticleVertexes = null;
  55898. this.id = name;
  55899. this.name = name;
  55900. this._capacity = capacity;
  55901. this._epsilon = epsilon;
  55902. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55903. if (isAnimationSheetEnabled) {
  55904. this._vertexBufferSize = 12;
  55905. }
  55906. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55907. this._customEffect = customEffect;
  55908. scene.particleSystems.push(this);
  55909. this._createIndexBuffer();
  55910. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  55911. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55912. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55913. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55914. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55915. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  55916. if (this._isAnimationSheetEnabled) {
  55917. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  55918. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55919. }
  55920. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55921. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55922. this._vertexBuffers["options"] = options;
  55923. // Default emitter type
  55924. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55925. this.updateFunction = function (particles) {
  55926. for (var index = 0; index < particles.length; index++) {
  55927. var particle = particles[index];
  55928. particle.age += _this._scaledUpdateSpeed;
  55929. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55930. _this._emitFromParticle(particle);
  55931. _this.recycleParticle(particle);
  55932. index--;
  55933. continue;
  55934. }
  55935. else {
  55936. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55937. particle.color.addInPlace(_this._scaledColorStep);
  55938. if (particle.color.a < 0)
  55939. particle.color.a = 0;
  55940. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55941. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55942. particle.position.addInPlace(_this._scaledDirection);
  55943. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55944. particle.direction.addInPlace(_this._scaledGravity);
  55945. if (_this._isAnimationSheetEnabled) {
  55946. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55947. }
  55948. }
  55949. }
  55950. };
  55951. }
  55952. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55953. /**
  55954. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55955. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55956. */
  55957. get: function () {
  55958. if (this.particleEmitterType.direction1) {
  55959. return this.particleEmitterType.direction1;
  55960. }
  55961. return BABYLON.Vector3.Zero();
  55962. },
  55963. set: function (value) {
  55964. if (this.particleEmitterType.direction1) {
  55965. this.particleEmitterType.direction1 = value;
  55966. }
  55967. },
  55968. enumerable: true,
  55969. configurable: true
  55970. });
  55971. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55972. /**
  55973. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55974. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55975. */
  55976. get: function () {
  55977. if (this.particleEmitterType.direction2) {
  55978. return this.particleEmitterType.direction2;
  55979. }
  55980. return BABYLON.Vector3.Zero();
  55981. },
  55982. set: function (value) {
  55983. if (this.particleEmitterType.direction2) {
  55984. this.particleEmitterType.direction2 = value;
  55985. }
  55986. },
  55987. enumerable: true,
  55988. configurable: true
  55989. });
  55990. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55991. /**
  55992. * 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.
  55993. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55994. */
  55995. get: function () {
  55996. if (this.particleEmitterType.minEmitBox) {
  55997. return this.particleEmitterType.minEmitBox;
  55998. }
  55999. return BABYLON.Vector3.Zero();
  56000. },
  56001. set: function (value) {
  56002. if (this.particleEmitterType.minEmitBox) {
  56003. this.particleEmitterType.minEmitBox = value;
  56004. }
  56005. },
  56006. enumerable: true,
  56007. configurable: true
  56008. });
  56009. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56010. /**
  56011. * 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.
  56012. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56013. */
  56014. get: function () {
  56015. if (this.particleEmitterType.maxEmitBox) {
  56016. return this.particleEmitterType.maxEmitBox;
  56017. }
  56018. return BABYLON.Vector3.Zero();
  56019. },
  56020. set: function (value) {
  56021. if (this.particleEmitterType.maxEmitBox) {
  56022. this.particleEmitterType.maxEmitBox = value;
  56023. }
  56024. },
  56025. enumerable: true,
  56026. configurable: true
  56027. });
  56028. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56029. /**
  56030. * Sets a callback that will be triggered when the system is disposed.
  56031. */
  56032. set: function (callback) {
  56033. if (this._onDisposeObserver) {
  56034. this.onDisposeObservable.remove(this._onDisposeObserver);
  56035. }
  56036. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56037. },
  56038. enumerable: true,
  56039. configurable: true
  56040. });
  56041. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56042. /**
  56043. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56044. */
  56045. get: function () {
  56046. return this._isAnimationSheetEnabled;
  56047. },
  56048. enumerable: true,
  56049. configurable: true
  56050. });
  56051. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56052. //end of Sub-emitter
  56053. /**
  56054. * Gets the current list of active particles
  56055. */
  56056. get: function () {
  56057. return this._particles;
  56058. },
  56059. enumerable: true,
  56060. configurable: true
  56061. });
  56062. /**
  56063. * Returns the string "ParticleSystem"
  56064. * @returns a string containing the class name
  56065. */
  56066. ParticleSystem.prototype.getClassName = function () {
  56067. return "ParticleSystem";
  56068. };
  56069. ParticleSystem.prototype._createIndexBuffer = function () {
  56070. var indices = [];
  56071. var index = 0;
  56072. for (var count = 0; count < this._capacity; count++) {
  56073. indices.push(index);
  56074. indices.push(index + 1);
  56075. indices.push(index + 2);
  56076. indices.push(index);
  56077. indices.push(index + 2);
  56078. indices.push(index + 3);
  56079. index += 4;
  56080. }
  56081. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56082. };
  56083. /**
  56084. * Gets the maximum number of particles active at the same time.
  56085. * @returns The max number of active particles.
  56086. */
  56087. ParticleSystem.prototype.getCapacity = function () {
  56088. return this._capacity;
  56089. };
  56090. /**
  56091. * Gets Wether there are still active particles in the system.
  56092. * @returns True if it is alive, otherwise false.
  56093. */
  56094. ParticleSystem.prototype.isAlive = function () {
  56095. return this._alive;
  56096. };
  56097. /**
  56098. * Gets Wether the system has been started.
  56099. * @returns True if it has been started, otherwise false.
  56100. */
  56101. ParticleSystem.prototype.isStarted = function () {
  56102. return this._started;
  56103. };
  56104. /**
  56105. * Starts the particle system and begins to emit.
  56106. */
  56107. ParticleSystem.prototype.start = function () {
  56108. this._started = true;
  56109. this._stopped = false;
  56110. this._actualFrame = 0;
  56111. if (this.subEmitters && this.subEmitters.length != 0) {
  56112. this.activeSubSystems = new Array();
  56113. }
  56114. };
  56115. /**
  56116. * Stops the particle system.
  56117. * @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.
  56118. */
  56119. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56120. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56121. this._stopped = true;
  56122. if (stopSubEmitters) {
  56123. this._stopSubEmitters();
  56124. }
  56125. };
  56126. // animation sheet
  56127. /**
  56128. * Remove all active particles
  56129. */
  56130. ParticleSystem.prototype.reset = function () {
  56131. this._stockParticles = [];
  56132. this._particles = [];
  56133. };
  56134. /**
  56135. * @hidden (for internal use only)
  56136. */
  56137. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56138. var offset = index * this._vertexBufferSize;
  56139. this._vertexData[offset] = particle.position.x;
  56140. this._vertexData[offset + 1] = particle.position.y;
  56141. this._vertexData[offset + 2] = particle.position.z;
  56142. this._vertexData[offset + 3] = particle.color.r;
  56143. this._vertexData[offset + 4] = particle.color.g;
  56144. this._vertexData[offset + 5] = particle.color.b;
  56145. this._vertexData[offset + 6] = particle.color.a;
  56146. this._vertexData[offset + 7] = particle.angle;
  56147. this._vertexData[offset + 8] = particle.size;
  56148. this._vertexData[offset + 9] = offsetX;
  56149. this._vertexData[offset + 10] = offsetY;
  56150. };
  56151. /**
  56152. * @hidden (for internal use only)
  56153. */
  56154. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56155. if (offsetX === 0)
  56156. offsetX = this._epsilon;
  56157. else if (offsetX === 1)
  56158. offsetX = 1 - this._epsilon;
  56159. if (offsetY === 0)
  56160. offsetY = this._epsilon;
  56161. else if (offsetY === 1)
  56162. offsetY = 1 - this._epsilon;
  56163. var offset = index * this._vertexBufferSize;
  56164. this._vertexData[offset] = particle.position.x;
  56165. this._vertexData[offset + 1] = particle.position.y;
  56166. this._vertexData[offset + 2] = particle.position.z;
  56167. this._vertexData[offset + 3] = particle.color.r;
  56168. this._vertexData[offset + 4] = particle.color.g;
  56169. this._vertexData[offset + 5] = particle.color.b;
  56170. this._vertexData[offset + 6] = particle.color.a;
  56171. this._vertexData[offset + 7] = particle.angle;
  56172. this._vertexData[offset + 8] = particle.size;
  56173. this._vertexData[offset + 9] = offsetX;
  56174. this._vertexData[offset + 10] = offsetY;
  56175. this._vertexData[offset + 11] = particle.cellIndex;
  56176. };
  56177. ParticleSystem.prototype._stopSubEmitters = function () {
  56178. if (!this.activeSubSystems) {
  56179. return;
  56180. }
  56181. this.activeSubSystems.forEach(function (subSystem) {
  56182. subSystem.stop(true);
  56183. });
  56184. this.activeSubSystems = new Array();
  56185. };
  56186. ParticleSystem.prototype._removeFromRoot = function () {
  56187. if (!this._rootParticleSystem) {
  56188. return;
  56189. }
  56190. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56191. if (index !== -1) {
  56192. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56193. }
  56194. };
  56195. // end of sub system methods
  56196. ParticleSystem.prototype._update = function (newParticles) {
  56197. // Update current
  56198. this._alive = this._particles.length > 0;
  56199. this.updateFunction(this._particles);
  56200. // Add new ones
  56201. var worldMatrix;
  56202. if (this.emitter.position) {
  56203. var emitterMesh = this.emitter;
  56204. worldMatrix = emitterMesh.getWorldMatrix();
  56205. }
  56206. else {
  56207. var emitterPosition = this.emitter;
  56208. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56209. }
  56210. var particle;
  56211. for (var index = 0; index < newParticles; index++) {
  56212. if (this._particles.length === this._capacity) {
  56213. break;
  56214. }
  56215. particle = this._createParticle();
  56216. this._particles.push(particle);
  56217. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56218. if (this.startPositionFunction) {
  56219. this.startPositionFunction(worldMatrix, particle.position, particle);
  56220. }
  56221. else {
  56222. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56223. }
  56224. if (this.startDirectionFunction) {
  56225. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56226. }
  56227. else {
  56228. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56229. }
  56230. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56231. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56232. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56233. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56234. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56235. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56236. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56237. }
  56238. };
  56239. ParticleSystem.prototype._getEffect = function () {
  56240. if (this._customEffect) {
  56241. return this._customEffect;
  56242. }
  56243. ;
  56244. var defines = [];
  56245. if (this._scene.clipPlane) {
  56246. defines.push("#define CLIPPLANE");
  56247. }
  56248. if (this._isAnimationSheetEnabled) {
  56249. defines.push("#define ANIMATESHEET");
  56250. }
  56251. // Effect
  56252. var join = defines.join("\n");
  56253. if (this._cachedDefines !== join) {
  56254. this._cachedDefines = join;
  56255. var attributesNamesOrOptions;
  56256. var effectCreationOption;
  56257. if (this._isAnimationSheetEnabled) {
  56258. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56259. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56260. }
  56261. else {
  56262. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56263. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56264. }
  56265. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56266. }
  56267. return this._effect;
  56268. };
  56269. /**
  56270. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56271. */
  56272. ParticleSystem.prototype.animate = function () {
  56273. if (!this._started)
  56274. return;
  56275. var effect = this._getEffect();
  56276. // Check
  56277. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56278. return;
  56279. if (this._currentRenderId === this._scene.getRenderId()) {
  56280. return;
  56281. }
  56282. this._currentRenderId = this._scene.getRenderId();
  56283. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56284. // determine the number of particles we need to create
  56285. var newParticles;
  56286. if (this.manualEmitCount > -1) {
  56287. newParticles = this.manualEmitCount;
  56288. this._newPartsExcess = 0;
  56289. this.manualEmitCount = 0;
  56290. }
  56291. else {
  56292. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56293. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56294. }
  56295. if (this._newPartsExcess > 1.0) {
  56296. newParticles += this._newPartsExcess >> 0;
  56297. this._newPartsExcess -= this._newPartsExcess >> 0;
  56298. }
  56299. this._alive = false;
  56300. if (!this._stopped) {
  56301. this._actualFrame += this._scaledUpdateSpeed;
  56302. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56303. this.stop();
  56304. }
  56305. else {
  56306. newParticles = 0;
  56307. }
  56308. this._update(newParticles);
  56309. // Stopped?
  56310. if (this._stopped) {
  56311. if (!this._alive) {
  56312. this._started = false;
  56313. if (this.onAnimationEnd) {
  56314. this.onAnimationEnd();
  56315. }
  56316. if (this.disposeOnStop) {
  56317. this._scene._toBeDisposed.push(this);
  56318. }
  56319. }
  56320. }
  56321. // Animation sheet
  56322. if (this._isAnimationSheetEnabled) {
  56323. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56324. }
  56325. else {
  56326. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56327. }
  56328. // Update VBO
  56329. var offset = 0;
  56330. for (var index = 0; index < this._particles.length; index++) {
  56331. var particle = this._particles[index];
  56332. this._appendParticleVertexes(offset, particle);
  56333. offset += 4;
  56334. }
  56335. if (this._vertexBuffer) {
  56336. this._vertexBuffer.update(this._vertexData);
  56337. }
  56338. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56339. this.stop();
  56340. }
  56341. };
  56342. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56343. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56344. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56345. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56346. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56347. };
  56348. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56349. this._appendParticleVertex(offset++, particle, 0, 0);
  56350. this._appendParticleVertex(offset++, particle, 1, 0);
  56351. this._appendParticleVertex(offset++, particle, 1, 1);
  56352. this._appendParticleVertex(offset++, particle, 0, 1);
  56353. };
  56354. /**
  56355. * Rebuilds the particle system.
  56356. */
  56357. ParticleSystem.prototype.rebuild = function () {
  56358. this._createIndexBuffer();
  56359. if (this._vertexBuffer) {
  56360. this._vertexBuffer._rebuild();
  56361. }
  56362. };
  56363. /**
  56364. * Is this system ready to be used/rendered
  56365. * @return true if the system is ready
  56366. */
  56367. ParticleSystem.prototype.isReady = function () {
  56368. var effect = this._getEffect();
  56369. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56370. return false;
  56371. }
  56372. return true;
  56373. };
  56374. /**
  56375. * Renders the particle system in its current state.
  56376. * @returns the current number of particles
  56377. */
  56378. ParticleSystem.prototype.render = function () {
  56379. var effect = this._getEffect();
  56380. // Check
  56381. if (!this.isReady() || !this._particles.length) {
  56382. return 0;
  56383. }
  56384. var engine = this._scene.getEngine();
  56385. // Render
  56386. engine.enableEffect(effect);
  56387. engine.setState(false);
  56388. var viewMatrix = this._scene.getViewMatrix();
  56389. effect.setTexture("diffuseSampler", this.particleTexture);
  56390. effect.setMatrix("view", viewMatrix);
  56391. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56392. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56393. var baseSize = this.particleTexture.getBaseSize();
  56394. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56395. }
  56396. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56397. if (this._scene.clipPlane) {
  56398. var clipPlane = this._scene.clipPlane;
  56399. var invView = viewMatrix.clone();
  56400. invView.invert();
  56401. effect.setMatrix("invView", invView);
  56402. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56403. }
  56404. // VBOs
  56405. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56406. // Draw order
  56407. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56408. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56409. }
  56410. else {
  56411. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56412. }
  56413. if (this.forceDepthWrite) {
  56414. engine.setDepthWrite(true);
  56415. }
  56416. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56417. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56418. return this._particles.length;
  56419. };
  56420. /**
  56421. * Disposes the particle system and free the associated resources
  56422. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56423. */
  56424. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56425. if (disposeTexture === void 0) { disposeTexture = true; }
  56426. if (this._vertexBuffer) {
  56427. this._vertexBuffer.dispose();
  56428. this._vertexBuffer = null;
  56429. }
  56430. if (this._indexBuffer) {
  56431. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56432. this._indexBuffer = null;
  56433. }
  56434. if (disposeTexture && this.particleTexture) {
  56435. this.particleTexture.dispose();
  56436. this.particleTexture = null;
  56437. }
  56438. this._removeFromRoot();
  56439. // Remove from scene
  56440. var index = this._scene.particleSystems.indexOf(this);
  56441. if (index > -1) {
  56442. this._scene.particleSystems.splice(index, 1);
  56443. }
  56444. // Callback
  56445. this.onDisposeObservable.notifyObservers(this);
  56446. this.onDisposeObservable.clear();
  56447. };
  56448. /**
  56449. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56450. * @param radius The radius of the sphere to emit from
  56451. * @returns the emitter
  56452. */
  56453. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56454. if (radius === void 0) { radius = 1; }
  56455. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56456. this.particleEmitterType = particleEmitter;
  56457. return particleEmitter;
  56458. };
  56459. /**
  56460. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56461. * @param radius The radius of the sphere to emit from
  56462. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56463. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56464. * @returns the emitter
  56465. */
  56466. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56467. if (radius === void 0) { radius = 1; }
  56468. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56469. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56470. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56471. this.particleEmitterType = particleEmitter;
  56472. return particleEmitter;
  56473. };
  56474. /**
  56475. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56476. * @param radius The radius of the cone to emit from
  56477. * @param angle The base angle of the cone
  56478. * @returns the emitter
  56479. */
  56480. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56481. if (radius === void 0) { radius = 1; }
  56482. if (angle === void 0) { angle = Math.PI / 4; }
  56483. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56484. this.particleEmitterType = particleEmitter;
  56485. return particleEmitter;
  56486. };
  56487. // 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.
  56488. /**
  56489. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56490. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56491. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56492. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56493. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56494. * @returns the emitter
  56495. */
  56496. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56497. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56498. this.particleEmitterType = particleEmitter;
  56499. this.direction1 = direction1;
  56500. this.direction2 = direction2;
  56501. this.minEmitBox = minEmitBox;
  56502. this.maxEmitBox = maxEmitBox;
  56503. return particleEmitter;
  56504. };
  56505. // Clone
  56506. /**
  56507. * Clones the particle system.
  56508. * @param name The name of the cloned object
  56509. * @param newEmitter The new emitter to use
  56510. * @returns the cloned particle system
  56511. */
  56512. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56513. var custom = null;
  56514. var program = null;
  56515. if (this.customShader != null) {
  56516. program = this.customShader;
  56517. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56518. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56519. }
  56520. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56521. result.customShader = program;
  56522. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56523. if (newEmitter === undefined) {
  56524. newEmitter = this.emitter;
  56525. }
  56526. result.emitter = newEmitter;
  56527. if (this.particleTexture) {
  56528. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56529. }
  56530. if (!this.preventAutoStart) {
  56531. result.start();
  56532. }
  56533. return result;
  56534. };
  56535. /**
  56536. * Serializes the particle system to a JSON object.
  56537. * @returns the JSON object
  56538. */
  56539. ParticleSystem.prototype.serialize = function () {
  56540. var serializationObject = {};
  56541. serializationObject.name = this.name;
  56542. serializationObject.id = this.id;
  56543. // Emitter
  56544. if (this.emitter.position) {
  56545. var emitterMesh = this.emitter;
  56546. serializationObject.emitterId = emitterMesh.id;
  56547. }
  56548. else {
  56549. var emitterPosition = this.emitter;
  56550. serializationObject.emitter = emitterPosition.asArray();
  56551. }
  56552. serializationObject.capacity = this.getCapacity();
  56553. if (this.particleTexture) {
  56554. serializationObject.textureName = this.particleTexture.name;
  56555. }
  56556. // Animations
  56557. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56558. // Particle system
  56559. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56560. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56561. serializationObject.minSize = this.minSize;
  56562. serializationObject.maxSize = this.maxSize;
  56563. serializationObject.minEmitPower = this.minEmitPower;
  56564. serializationObject.maxEmitPower = this.maxEmitPower;
  56565. serializationObject.minLifeTime = this.minLifeTime;
  56566. serializationObject.maxLifeTime = this.maxLifeTime;
  56567. serializationObject.emitRate = this.emitRate;
  56568. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56569. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56570. serializationObject.gravity = this.gravity.asArray();
  56571. serializationObject.direction1 = this.direction1.asArray();
  56572. serializationObject.direction2 = this.direction2.asArray();
  56573. serializationObject.color1 = this.color1.asArray();
  56574. serializationObject.color2 = this.color2.asArray();
  56575. serializationObject.colorDead = this.colorDead.asArray();
  56576. serializationObject.updateSpeed = this.updateSpeed;
  56577. serializationObject.targetStopDuration = this.targetStopDuration;
  56578. serializationObject.textureMask = this.textureMask.asArray();
  56579. serializationObject.blendMode = this.blendMode;
  56580. serializationObject.customShader = this.customShader;
  56581. serializationObject.preventAutoStart = this.preventAutoStart;
  56582. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56583. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56584. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56585. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56586. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56587. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56588. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56589. // Emitter
  56590. if (this.particleEmitterType) {
  56591. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56592. }
  56593. return serializationObject;
  56594. };
  56595. /**
  56596. * Parses a JSON object to create a particle system.
  56597. * @param parsedParticleSystem The JSON object to parse
  56598. * @param scene The scene to create the particle system in
  56599. * @param rootUrl The root url to use to load external dependencies like texture
  56600. * @returns the Parsed particle system
  56601. */
  56602. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56603. var name = parsedParticleSystem.name;
  56604. var custom = null;
  56605. var program = null;
  56606. if (parsedParticleSystem.customShader) {
  56607. program = parsedParticleSystem.customShader;
  56608. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56609. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56610. }
  56611. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56612. particleSystem.customShader = program;
  56613. if (parsedParticleSystem.id) {
  56614. particleSystem.id = parsedParticleSystem.id;
  56615. }
  56616. // Auto start
  56617. if (parsedParticleSystem.preventAutoStart) {
  56618. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56619. }
  56620. // Texture
  56621. if (parsedParticleSystem.textureName) {
  56622. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56623. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56624. }
  56625. // Emitter
  56626. if (parsedParticleSystem.emitterId) {
  56627. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56628. }
  56629. else {
  56630. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56631. }
  56632. // Animations
  56633. if (parsedParticleSystem.animations) {
  56634. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56635. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56636. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56637. }
  56638. }
  56639. if (parsedParticleSystem.autoAnimate) {
  56640. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56641. }
  56642. // Particle system
  56643. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56644. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56645. particleSystem.minSize = parsedParticleSystem.minSize;
  56646. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56647. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56648. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56649. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56650. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56651. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56652. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56653. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56654. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56655. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56656. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56657. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56658. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56659. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56660. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56661. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56662. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56663. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56664. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56665. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56666. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56667. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56668. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56669. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56670. if (!particleSystem.preventAutoStart) {
  56671. particleSystem.start();
  56672. }
  56673. return particleSystem;
  56674. };
  56675. /**
  56676. * Source color is added to the destination color without alpha affecting the result.
  56677. */
  56678. ParticleSystem.BLENDMODE_ONEONE = 0;
  56679. /**
  56680. * Blend current color and particle color using particle’s alpha.
  56681. */
  56682. ParticleSystem.BLENDMODE_STANDARD = 1;
  56683. return ParticleSystem;
  56684. }());
  56685. BABYLON.ParticleSystem = ParticleSystem;
  56686. })(BABYLON || (BABYLON = {}));
  56687. //# sourceMappingURL=babylon.particleSystem.js.map
  56688. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56689. var BABYLON;
  56690. (function (BABYLON) {
  56691. /**
  56692. * Particle emitter emitting particles from the inside of a box.
  56693. * It emits the particles randomly between 2 given directions.
  56694. */
  56695. var BoxParticleEmitter = /** @class */ (function () {
  56696. /**
  56697. * Creates a new instance BoxParticleEmitter
  56698. */
  56699. function BoxParticleEmitter() {
  56700. /**
  56701. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56702. */
  56703. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56704. /**
  56705. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56706. */
  56707. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56708. /**
  56709. * 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.
  56710. */
  56711. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56712. /**
  56713. * 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.
  56714. */
  56715. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56716. }
  56717. /**
  56718. * Called by the particle System when the direction is computed for the created particle.
  56719. * @param emitPower is the power of the particle (speed)
  56720. * @param worldMatrix is the world matrix of the particle system
  56721. * @param directionToUpdate is the direction vector to update with the result
  56722. * @param particle is the particle we are computed the direction for
  56723. */
  56724. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56725. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56726. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56727. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56728. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56729. };
  56730. /**
  56731. * Called by the particle System when the position is computed for the created particle.
  56732. * @param worldMatrix is the world matrix of the particle system
  56733. * @param positionToUpdate is the position vector to update with the result
  56734. * @param particle is the particle we are computed the position for
  56735. */
  56736. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56737. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56738. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56739. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56740. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56741. };
  56742. /**
  56743. * Clones the current emitter and returns a copy of it
  56744. * @returns the new emitter
  56745. */
  56746. BoxParticleEmitter.prototype.clone = function () {
  56747. var newOne = new BoxParticleEmitter();
  56748. BABYLON.Tools.DeepCopy(this, newOne);
  56749. return newOne;
  56750. };
  56751. /**
  56752. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56753. * @param effect defines the update shader
  56754. */
  56755. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56756. effect.setVector3("direction1", this.direction1);
  56757. effect.setVector3("direction2", this.direction2);
  56758. effect.setVector3("minEmitBox", this.minEmitBox);
  56759. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56760. };
  56761. /**
  56762. * Returns a string to use to update the GPU particles update shader
  56763. * @returns a string containng the defines string
  56764. */
  56765. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56766. return "#define BOXEMITTER";
  56767. };
  56768. /**
  56769. * Returns the string "BoxEmitter"
  56770. * @returns a string containing the class name
  56771. */
  56772. BoxParticleEmitter.prototype.getClassName = function () {
  56773. return "BoxEmitter";
  56774. };
  56775. /**
  56776. * Serializes the particle system to a JSON object.
  56777. * @returns the JSON object
  56778. */
  56779. BoxParticleEmitter.prototype.serialize = function () {
  56780. var serializationObject = {};
  56781. serializationObject.type = this.getClassName();
  56782. serializationObject.direction1 = this.direction1.asArray();
  56783. serializationObject.direction2 = this.direction2.asArray();
  56784. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56785. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56786. return serializationObject;
  56787. };
  56788. /**
  56789. * Parse properties from a JSON object
  56790. * @param serializationObject defines the JSON object
  56791. */
  56792. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56793. this.direction1.copyFrom(serializationObject.direction1);
  56794. this.direction2.copyFrom(serializationObject.direction2);
  56795. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56796. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56797. };
  56798. return BoxParticleEmitter;
  56799. }());
  56800. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56801. })(BABYLON || (BABYLON = {}));
  56802. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56803. var BABYLON;
  56804. (function (BABYLON) {
  56805. /**
  56806. * Particle emitter emitting particles from the inside of a cone.
  56807. * It emits the particles alongside the cone volume from the base to the particle.
  56808. * The emission direction might be randomized.
  56809. */
  56810. var ConeParticleEmitter = /** @class */ (function () {
  56811. /**
  56812. * Creates a new instance ConeParticleEmitter
  56813. * @param radius the radius of the emission cone (1 by default)
  56814. * @param angles the cone base angle (PI by default)
  56815. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56816. */
  56817. function ConeParticleEmitter(radius,
  56818. /**
  56819. * The radius of the emission cone.
  56820. */
  56821. angle,
  56822. /**
  56823. * The cone base angle.
  56824. */
  56825. directionRandomizer) {
  56826. if (radius === void 0) { radius = 1; }
  56827. if (angle === void 0) { angle = Math.PI; }
  56828. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56829. this.angle = angle;
  56830. this.directionRandomizer = directionRandomizer;
  56831. this.radius = radius;
  56832. }
  56833. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56834. /**
  56835. * Gets the radius of the emission cone.
  56836. */
  56837. get: function () {
  56838. return this._radius;
  56839. },
  56840. /**
  56841. * Sets the radius of the emission cone.
  56842. */
  56843. set: function (value) {
  56844. this._radius = value;
  56845. if (this.angle !== 0) {
  56846. this._height = value / Math.tan(this.angle / 2);
  56847. }
  56848. else {
  56849. this._height = 1;
  56850. }
  56851. },
  56852. enumerable: true,
  56853. configurable: true
  56854. });
  56855. /**
  56856. * Called by the particle System when the direction is computed for the created particle.
  56857. * @param emitPower is the power of the particle (speed)
  56858. * @param worldMatrix is the world matrix of the particle system
  56859. * @param directionToUpdate is the direction vector to update with the result
  56860. * @param particle is the particle we are computed the direction for
  56861. */
  56862. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56863. if (this.angle === 0) {
  56864. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56865. }
  56866. else {
  56867. // measure the direction Vector from the emitter to the particle.
  56868. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56869. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56870. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56871. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56872. direction.x += randX;
  56873. direction.y += randY;
  56874. direction.z += randZ;
  56875. direction.normalize();
  56876. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56877. }
  56878. };
  56879. /**
  56880. * Called by the particle System when the position is computed for the created particle.
  56881. * @param worldMatrix is the world matrix of the particle system
  56882. * @param positionToUpdate is the position vector to update with the result
  56883. * @param particle is the particle we are computed the position for
  56884. */
  56885. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56886. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56887. var h = BABYLON.Scalar.RandomRange(0, 1);
  56888. // Better distribution in a cone at normal angles.
  56889. h = 1 - h * h;
  56890. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56891. radius = radius * h;
  56892. var randX = radius * Math.sin(s);
  56893. var randZ = radius * Math.cos(s);
  56894. var randY = h * this._height;
  56895. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56896. };
  56897. /**
  56898. * Clones the current emitter and returns a copy of it
  56899. * @returns the new emitter
  56900. */
  56901. ConeParticleEmitter.prototype.clone = function () {
  56902. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  56903. BABYLON.Tools.DeepCopy(this, newOne);
  56904. return newOne;
  56905. };
  56906. /**
  56907. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56908. * @param effect defines the update shader
  56909. */
  56910. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56911. effect.setFloat("radius", this.radius);
  56912. effect.setFloat("angle", this.angle);
  56913. effect.setFloat("height", this._height);
  56914. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56915. };
  56916. /**
  56917. * Returns a string to use to update the GPU particles update shader
  56918. * @returns a string containng the defines string
  56919. */
  56920. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56921. return "#define CONEEMITTER";
  56922. };
  56923. /**
  56924. * Returns the string "BoxEmitter"
  56925. * @returns a string containing the class name
  56926. */
  56927. ConeParticleEmitter.prototype.getClassName = function () {
  56928. return "ConeEmitter";
  56929. };
  56930. /**
  56931. * Serializes the particle system to a JSON object.
  56932. * @returns the JSON object
  56933. */
  56934. ConeParticleEmitter.prototype.serialize = function () {
  56935. var serializationObject = {};
  56936. serializationObject.type = this.getClassName();
  56937. serializationObject.radius = this.radius;
  56938. serializationObject.angle = this.angle;
  56939. serializationObject.directionRandomizer = this.directionRandomizer;
  56940. return serializationObject;
  56941. };
  56942. /**
  56943. * Parse properties from a JSON object
  56944. * @param serializationObject defines the JSON object
  56945. */
  56946. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56947. this.radius = serializationObject.radius;
  56948. this.angle = serializationObject.angle;
  56949. this.directionRandomizer = serializationObject.directionRandomizer;
  56950. };
  56951. return ConeParticleEmitter;
  56952. }());
  56953. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56954. })(BABYLON || (BABYLON = {}));
  56955. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56956. var BABYLON;
  56957. (function (BABYLON) {
  56958. /**
  56959. * Particle emitter emitting particles from the inside of a sphere.
  56960. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56961. */
  56962. var SphereParticleEmitter = /** @class */ (function () {
  56963. /**
  56964. * Creates a new instance SphereParticleEmitter
  56965. * @param radius the radius of the emission sphere (1 by default)
  56966. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56967. */
  56968. function SphereParticleEmitter(
  56969. /**
  56970. * The radius of the emission sphere.
  56971. */
  56972. radius,
  56973. /**
  56974. * How much to randomize the particle direction [0-1].
  56975. */
  56976. directionRandomizer) {
  56977. if (radius === void 0) { radius = 1; }
  56978. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56979. this.radius = radius;
  56980. this.directionRandomizer = directionRandomizer;
  56981. }
  56982. /**
  56983. * Called by the particle System when the direction is computed for the created particle.
  56984. * @param emitPower is the power of the particle (speed)
  56985. * @param worldMatrix is the world matrix of the particle system
  56986. * @param directionToUpdate is the direction vector to update with the result
  56987. * @param particle is the particle we are computed the direction for
  56988. */
  56989. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56990. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56991. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56992. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56993. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56994. direction.x += randX;
  56995. direction.y += randY;
  56996. direction.z += randZ;
  56997. direction.normalize();
  56998. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56999. };
  57000. /**
  57001. * Called by the particle System when the position is computed for the created particle.
  57002. * @param worldMatrix is the world matrix of the particle system
  57003. * @param positionToUpdate is the position vector to update with the result
  57004. * @param particle is the particle we are computed the position for
  57005. */
  57006. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57007. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57008. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57009. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57010. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57011. var randY = randRadius * Math.cos(theta);
  57012. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57013. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57014. };
  57015. /**
  57016. * Clones the current emitter and returns a copy of it
  57017. * @returns the new emitter
  57018. */
  57019. SphereParticleEmitter.prototype.clone = function () {
  57020. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57021. BABYLON.Tools.DeepCopy(this, newOne);
  57022. return newOne;
  57023. };
  57024. /**
  57025. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57026. * @param effect defines the update shader
  57027. */
  57028. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57029. effect.setFloat("radius", this.radius);
  57030. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57031. };
  57032. /**
  57033. * Returns a string to use to update the GPU particles update shader
  57034. * @returns a string containng the defines string
  57035. */
  57036. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57037. return "#define SPHEREEMITTER";
  57038. };
  57039. /**
  57040. * Returns the string "SphereParticleEmitter"
  57041. * @returns a string containing the class name
  57042. */
  57043. SphereParticleEmitter.prototype.getClassName = function () {
  57044. return "SphereParticleEmitter";
  57045. };
  57046. /**
  57047. * Serializes the particle system to a JSON object.
  57048. * @returns the JSON object
  57049. */
  57050. SphereParticleEmitter.prototype.serialize = function () {
  57051. var serializationObject = {};
  57052. serializationObject.type = this.getClassName();
  57053. serializationObject.radius = this.radius;
  57054. serializationObject.directionRandomizer = this.directionRandomizer;
  57055. return serializationObject;
  57056. };
  57057. /**
  57058. * Parse properties from a JSON object
  57059. * @param serializationObject defines the JSON object
  57060. */
  57061. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57062. this.radius = serializationObject.radius;
  57063. this.directionRandomizer = serializationObject.directionRandomizer;
  57064. };
  57065. return SphereParticleEmitter;
  57066. }());
  57067. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57068. /**
  57069. * Particle emitter emitting particles from the inside of a sphere.
  57070. * It emits the particles randomly between two vectors.
  57071. */
  57072. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57073. __extends(SphereDirectedParticleEmitter, _super);
  57074. /**
  57075. * Creates a new instance SphereDirectedParticleEmitter
  57076. * @param radius the radius of the emission sphere (1 by default)
  57077. * @param direction1 the min limit of the emission direction (up vector by default)
  57078. * @param direction2 the max limit of the emission direction (up vector by default)
  57079. */
  57080. function SphereDirectedParticleEmitter(radius,
  57081. /**
  57082. * The min limit of the emission direction.
  57083. */
  57084. direction1,
  57085. /**
  57086. * The max limit of the emission direction.
  57087. */
  57088. direction2) {
  57089. if (radius === void 0) { radius = 1; }
  57090. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57091. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57092. var _this = _super.call(this, radius) || this;
  57093. _this.direction1 = direction1;
  57094. _this.direction2 = direction2;
  57095. return _this;
  57096. }
  57097. /**
  57098. * Called by the particle System when the direction is computed for the created particle.
  57099. * @param emitPower is the power of the particle (speed)
  57100. * @param worldMatrix is the world matrix of the particle system
  57101. * @param directionToUpdate is the direction vector to update with the result
  57102. * @param particle is the particle we are computed the direction for
  57103. */
  57104. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57105. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57106. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57107. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57108. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57109. };
  57110. /**
  57111. * Clones the current emitter and returns a copy of it
  57112. * @returns the new emitter
  57113. */
  57114. SphereDirectedParticleEmitter.prototype.clone = function () {
  57115. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57116. BABYLON.Tools.DeepCopy(this, newOne);
  57117. return newOne;
  57118. };
  57119. /**
  57120. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57121. * @param effect defines the update shader
  57122. */
  57123. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57124. effect.setFloat("radius", this.radius);
  57125. effect.setVector3("direction1", this.direction1);
  57126. effect.setVector3("direction2", this.direction2);
  57127. };
  57128. /**
  57129. * Returns a string to use to update the GPU particles update shader
  57130. * @returns a string containng the defines string
  57131. */
  57132. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57133. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57134. };
  57135. /**
  57136. * Returns the string "SphereDirectedParticleEmitter"
  57137. * @returns a string containing the class name
  57138. */
  57139. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57140. return "SphereDirectedParticleEmitter";
  57141. };
  57142. /**
  57143. * Serializes the particle system to a JSON object.
  57144. * @returns the JSON object
  57145. */
  57146. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57147. var serializationObject = _super.prototype.serialize.call(this);
  57148. serializationObject.direction1 = this.direction1.asArray();
  57149. serializationObject.direction2 = this.direction2.asArray();
  57150. return serializationObject;
  57151. };
  57152. /**
  57153. * Parse properties from a JSON object
  57154. * @param serializationObject defines the JSON object
  57155. */
  57156. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57157. _super.prototype.parse.call(this, serializationObject);
  57158. this.direction1.copyFrom(serializationObject.direction1);
  57159. this.direction2.copyFrom(serializationObject.direction2);
  57160. };
  57161. return SphereDirectedParticleEmitter;
  57162. }(SphereParticleEmitter));
  57163. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57164. })(BABYLON || (BABYLON = {}));
  57165. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57166. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57167. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57168. s = arguments[i];
  57169. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57170. t[p] = s[p];
  57171. }
  57172. return t;
  57173. };
  57174. var BABYLON;
  57175. (function (BABYLON) {
  57176. /**
  57177. * This represents a GPU particle system in Babylon
  57178. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57179. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57180. */
  57181. var GPUParticleSystem = /** @class */ (function () {
  57182. /**
  57183. * Instantiates a GPU particle system.
  57184. * 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.
  57185. * @param name The name of the particle system
  57186. * @param capacity The max number of particles alive at the same time
  57187. * @param scene The scene the particle system belongs to
  57188. */
  57189. function GPUParticleSystem(name, options, scene) {
  57190. /**
  57191. * The emitter represents the Mesh or position we are attaching the particle system to.
  57192. */
  57193. this.emitter = null;
  57194. /**
  57195. * The rendering group used by the Particle system to chose when to render.
  57196. */
  57197. this.renderingGroupId = 0;
  57198. /**
  57199. * The layer mask we are rendering the particles through.
  57200. */
  57201. this.layerMask = 0x0FFFFFFF;
  57202. this._targetIndex = 0;
  57203. this._currentRenderId = -1;
  57204. this._started = false;
  57205. this._stopped = false;
  57206. this._timeDelta = 0;
  57207. this._attributesStrideSize = 14;
  57208. this._actualFrame = 0;
  57209. /**
  57210. * List of animations used by the particle system.
  57211. */
  57212. this.animations = [];
  57213. /**
  57214. * An event triggered when the system is disposed.
  57215. */
  57216. this.onDisposeObservable = new BABYLON.Observable();
  57217. /**
  57218. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57219. */
  57220. this.updateSpeed = 0.01;
  57221. /**
  57222. * The amount of time the particle system is running (depends of the overall update speed).
  57223. */
  57224. this.targetStopDuration = 0;
  57225. /**
  57226. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57227. */
  57228. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57229. /**
  57230. * Minimum life time of emitting particles.
  57231. */
  57232. this.minLifeTime = 1;
  57233. /**
  57234. * Maximum life time of emitting particles.
  57235. */
  57236. this.maxLifeTime = 1;
  57237. /**
  57238. * Minimum Size of emitting particles.
  57239. */
  57240. this.minSize = 1;
  57241. /**
  57242. * Maximum Size of emitting particles.
  57243. */
  57244. this.maxSize = 1;
  57245. /**
  57246. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57247. */
  57248. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57249. /**
  57250. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57251. */
  57252. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57253. /**
  57254. * Color the particle will have at the end of its lifetime.
  57255. */
  57256. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57257. /**
  57258. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57259. */
  57260. this.emitRate = 100;
  57261. /**
  57262. * You can use gravity if you want to give an orientation to your particles.
  57263. */
  57264. this.gravity = BABYLON.Vector3.Zero();
  57265. /**
  57266. * Minimum power of emitting particles.
  57267. */
  57268. this.minEmitPower = 1;
  57269. /**
  57270. * Maximum power of emitting particles.
  57271. */
  57272. this.maxEmitPower = 1;
  57273. /**
  57274. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57275. * to override the particles.
  57276. */
  57277. this.forceDepthWrite = false;
  57278. this.id = name;
  57279. this.name = name;
  57280. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57281. this._engine = this._scene.getEngine();
  57282. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57283. this._capacity = fullOptions.capacity;
  57284. this._activeCount = fullOptions.capacity;
  57285. this._currentActiveCount = 0;
  57286. this._scene.particleSystems.push(this);
  57287. this._updateEffectOptions = {
  57288. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  57289. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57290. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  57291. uniformBuffersNames: [],
  57292. samplers: ["randomSampler"],
  57293. defines: "",
  57294. fallbacks: null,
  57295. onCompiled: null,
  57296. onError: null,
  57297. indexParameters: null,
  57298. maxSimultaneousLights: 0,
  57299. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  57300. };
  57301. // Random data
  57302. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57303. var d = [];
  57304. for (var i = 0; i < maxTextureSize; ++i) {
  57305. d.push(Math.random());
  57306. d.push(Math.random());
  57307. d.push(Math.random());
  57308. d.push(Math.random());
  57309. }
  57310. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57311. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57312. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57313. this._randomTextureSize = maxTextureSize;
  57314. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57315. }
  57316. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57317. /**
  57318. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57319. */
  57320. get: function () {
  57321. if (!BABYLON.Engine.LastCreatedEngine) {
  57322. return false;
  57323. }
  57324. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57325. },
  57326. enumerable: true,
  57327. configurable: true
  57328. });
  57329. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57330. /**
  57331. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57332. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57333. */
  57334. get: function () {
  57335. if (this.particleEmitterType.direction1) {
  57336. return this.particleEmitterType.direction1;
  57337. }
  57338. return BABYLON.Vector3.Zero();
  57339. },
  57340. set: function (value) {
  57341. if (this.particleEmitterType.direction1) {
  57342. this.particleEmitterType.direction1 = value;
  57343. }
  57344. },
  57345. enumerable: true,
  57346. configurable: true
  57347. });
  57348. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57349. /**
  57350. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57351. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57352. */
  57353. get: function () {
  57354. if (this.particleEmitterType.direction2) {
  57355. return this.particleEmitterType.direction2;
  57356. }
  57357. return BABYLON.Vector3.Zero();
  57358. },
  57359. set: function (value) {
  57360. if (this.particleEmitterType.direction2) {
  57361. this.particleEmitterType.direction2 = value;
  57362. }
  57363. },
  57364. enumerable: true,
  57365. configurable: true
  57366. });
  57367. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57368. /**
  57369. * 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.
  57370. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57371. */
  57372. get: function () {
  57373. if (this.particleEmitterType.minEmitBox) {
  57374. return this.particleEmitterType.minEmitBox;
  57375. }
  57376. return BABYLON.Vector3.Zero();
  57377. },
  57378. set: function (value) {
  57379. if (this.particleEmitterType.minEmitBox) {
  57380. this.particleEmitterType.minEmitBox = value;
  57381. }
  57382. },
  57383. enumerable: true,
  57384. configurable: true
  57385. });
  57386. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57387. /**
  57388. * 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.
  57389. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57390. */
  57391. get: function () {
  57392. if (this.particleEmitterType.maxEmitBox) {
  57393. return this.particleEmitterType.maxEmitBox;
  57394. }
  57395. return BABYLON.Vector3.Zero();
  57396. },
  57397. set: function (value) {
  57398. if (this.particleEmitterType.maxEmitBox) {
  57399. this.particleEmitterType.maxEmitBox = value;
  57400. }
  57401. },
  57402. enumerable: true,
  57403. configurable: true
  57404. });
  57405. /**
  57406. * Gets the maximum number of particles active at the same time.
  57407. * @returns The max number of active particles.
  57408. */
  57409. GPUParticleSystem.prototype.getCapacity = function () {
  57410. return this._capacity;
  57411. };
  57412. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57413. /**
  57414. * Gets or set the number of active particles
  57415. */
  57416. get: function () {
  57417. return this._activeCount;
  57418. },
  57419. set: function (value) {
  57420. this._activeCount = Math.min(value, this._capacity);
  57421. },
  57422. enumerable: true,
  57423. configurable: true
  57424. });
  57425. /**
  57426. * Is this system ready to be used/rendered
  57427. * @return true if the system is ready
  57428. */
  57429. GPUParticleSystem.prototype.isReady = function () {
  57430. if (!this._updateEffect) {
  57431. this._recreateUpdateEffect();
  57432. this._recreateRenderEffect();
  57433. return false;
  57434. }
  57435. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57436. return false;
  57437. }
  57438. return true;
  57439. };
  57440. /**
  57441. * Gets Wether the system has been started.
  57442. * @returns True if it has been started, otherwise false.
  57443. */
  57444. GPUParticleSystem.prototype.isStarted = function () {
  57445. return this._started;
  57446. };
  57447. /**
  57448. * Starts the particle system and begins to emit.
  57449. */
  57450. GPUParticleSystem.prototype.start = function () {
  57451. this._started = true;
  57452. this._stopped = false;
  57453. };
  57454. /**
  57455. * Stops the particle system.
  57456. */
  57457. GPUParticleSystem.prototype.stop = function () {
  57458. this._stopped = true;
  57459. };
  57460. /**
  57461. * Remove all active particles
  57462. */
  57463. GPUParticleSystem.prototype.reset = function () {
  57464. this._releaseBuffers();
  57465. this._releaseVAOs();
  57466. this._currentActiveCount = 0;
  57467. this._targetIndex = 0;
  57468. };
  57469. /**
  57470. * Returns the string "GPUParticleSystem"
  57471. * @returns a string containing the class name
  57472. */
  57473. GPUParticleSystem.prototype.getClassName = function () {
  57474. return "GPUParticleSystem";
  57475. };
  57476. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57477. var updateVertexBuffers = {};
  57478. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57479. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57480. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57481. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57482. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57483. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57484. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57485. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57486. this._engine.bindArrayBuffer(null);
  57487. return vao;
  57488. };
  57489. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57490. var renderVertexBuffers = {};
  57491. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57492. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57493. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57494. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57495. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57496. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57497. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57498. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57499. this._engine.bindArrayBuffer(null);
  57500. return vao;
  57501. };
  57502. GPUParticleSystem.prototype._initialize = function (force) {
  57503. if (force === void 0) { force = false; }
  57504. if (this._buffer0 && !force) {
  57505. return;
  57506. }
  57507. var engine = this._scene.getEngine();
  57508. var data = new Array();
  57509. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57510. // position
  57511. data.push(0.0);
  57512. data.push(0.0);
  57513. data.push(0.0);
  57514. // Age and life
  57515. data.push(0.0); // create the particle as a dead one to create a new one at start
  57516. data.push(0.0);
  57517. // Seed
  57518. data.push(Math.random());
  57519. // Size
  57520. data.push(0.0);
  57521. // color
  57522. data.push(0.0);
  57523. data.push(0.0);
  57524. data.push(0.0);
  57525. data.push(0.0);
  57526. // direction
  57527. data.push(0.0);
  57528. data.push(0.0);
  57529. data.push(0.0);
  57530. }
  57531. // Sprite data
  57532. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57533. -0.5, 0.5, 0, 1,
  57534. -0.5, -0.5, 0, 0,
  57535. 0.5, -0.5, 1, 0]);
  57536. // Buffers
  57537. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57538. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57539. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57540. // Update VAO
  57541. this._updateVAO = [];
  57542. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57543. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57544. // Render VAO
  57545. this._renderVAO = [];
  57546. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57547. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57548. // Links
  57549. this._sourceBuffer = this._buffer0;
  57550. this._targetBuffer = this._buffer1;
  57551. };
  57552. /** @hidden */
  57553. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57554. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57555. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57556. return;
  57557. }
  57558. this._updateEffectOptions.defines = defines;
  57559. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57560. };
  57561. /** @hidden */
  57562. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57563. var defines = "";
  57564. if (this._scene.clipPlane) {
  57565. defines = "\n#define CLIPPLANE";
  57566. }
  57567. if (this._renderEffect && this._renderEffect.defines === defines) {
  57568. return;
  57569. }
  57570. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57571. };
  57572. /**
  57573. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57574. */
  57575. GPUParticleSystem.prototype.animate = function () {
  57576. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57577. this._actualFrame += this._timeDelta;
  57578. if (!this._stopped) {
  57579. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57580. this.stop();
  57581. }
  57582. }
  57583. };
  57584. /**
  57585. * Renders the particle system in its current state.
  57586. * @returns the current number of particles
  57587. */
  57588. GPUParticleSystem.prototype.render = function () {
  57589. if (!this._started) {
  57590. return 0;
  57591. }
  57592. this._recreateUpdateEffect();
  57593. this._recreateRenderEffect();
  57594. if (!this.isReady()) {
  57595. return 0;
  57596. }
  57597. if (this._currentRenderId === this._scene.getRenderId()) {
  57598. return 0;
  57599. }
  57600. this._currentRenderId = this._scene.getRenderId();
  57601. // Get everything ready to render
  57602. this._initialize();
  57603. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57604. // Enable update effect
  57605. this._engine.enableEffect(this._updateEffect);
  57606. this._engine.setState(false);
  57607. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57608. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57609. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57610. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57611. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57612. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57613. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57614. this._updateEffect.setDirectColor4("color1", this.color1);
  57615. this._updateEffect.setDirectColor4("color2", this.color2);
  57616. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57617. this._updateEffect.setVector3("gravity", this.gravity);
  57618. if (this.particleEmitterType) {
  57619. this.particleEmitterType.applyToShader(this._updateEffect);
  57620. }
  57621. var emitterWM;
  57622. if (this.emitter.position) {
  57623. var emitterMesh = this.emitter;
  57624. emitterWM = emitterMesh.getWorldMatrix();
  57625. }
  57626. else {
  57627. var emitterPosition = this.emitter;
  57628. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57629. }
  57630. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57631. // Bind source VAO
  57632. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57633. // Update
  57634. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57635. this._engine.setRasterizerState(false);
  57636. this._engine.beginTransformFeedback();
  57637. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57638. this._engine.endTransformFeedback();
  57639. this._engine.setRasterizerState(true);
  57640. this._engine.bindTransformFeedbackBuffer(null);
  57641. // Enable render effect
  57642. this._engine.enableEffect(this._renderEffect);
  57643. var viewMatrix = this._scene.getViewMatrix();
  57644. this._renderEffect.setMatrix("view", viewMatrix);
  57645. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57646. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57647. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57648. if (this._scene.clipPlane) {
  57649. var clipPlane = this._scene.clipPlane;
  57650. var invView = viewMatrix.clone();
  57651. invView.invert();
  57652. this._renderEffect.setMatrix("invView", invView);
  57653. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57654. }
  57655. // Draw order
  57656. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57657. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57658. }
  57659. else {
  57660. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57661. }
  57662. if (this.forceDepthWrite) {
  57663. this._engine.setDepthWrite(true);
  57664. }
  57665. // Bind source VAO
  57666. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57667. // Render
  57668. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57669. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57670. // Switch VAOs
  57671. this._targetIndex++;
  57672. if (this._targetIndex === 2) {
  57673. this._targetIndex = 0;
  57674. }
  57675. // Switch buffers
  57676. var tmpBuffer = this._sourceBuffer;
  57677. this._sourceBuffer = this._targetBuffer;
  57678. this._targetBuffer = tmpBuffer;
  57679. return this._currentActiveCount;
  57680. };
  57681. /**
  57682. * Rebuilds the particle system
  57683. */
  57684. GPUParticleSystem.prototype.rebuild = function () {
  57685. this._initialize(true);
  57686. };
  57687. GPUParticleSystem.prototype._releaseBuffers = function () {
  57688. if (this._buffer0) {
  57689. this._buffer0.dispose();
  57690. this._buffer0 = null;
  57691. }
  57692. if (this._buffer1) {
  57693. this._buffer1.dispose();
  57694. this._buffer1 = null;
  57695. }
  57696. if (this._spriteBuffer) {
  57697. this._spriteBuffer.dispose();
  57698. this._spriteBuffer = null;
  57699. }
  57700. };
  57701. GPUParticleSystem.prototype._releaseVAOs = function () {
  57702. if (!this._updateVAO) {
  57703. return;
  57704. }
  57705. for (var index = 0; index < this._updateVAO.length; index++) {
  57706. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57707. }
  57708. this._updateVAO = [];
  57709. for (var index = 0; index < this._renderVAO.length; index++) {
  57710. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57711. }
  57712. this._renderVAO = [];
  57713. };
  57714. /**
  57715. * Disposes the particle system and free the associated resources
  57716. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57717. */
  57718. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57719. if (disposeTexture === void 0) { disposeTexture = true; }
  57720. var index = this._scene.particleSystems.indexOf(this);
  57721. if (index > -1) {
  57722. this._scene.particleSystems.splice(index, 1);
  57723. }
  57724. this._releaseBuffers();
  57725. this._releaseVAOs();
  57726. if (this._randomTexture) {
  57727. this._randomTexture.dispose();
  57728. this._randomTexture = null;
  57729. }
  57730. if (disposeTexture && this.particleTexture) {
  57731. this.particleTexture.dispose();
  57732. this.particleTexture = null;
  57733. }
  57734. // Callback
  57735. this.onDisposeObservable.notifyObservers(this);
  57736. this.onDisposeObservable.clear();
  57737. };
  57738. /**
  57739. * Clones the particle system.
  57740. * @param name The name of the cloned object
  57741. * @param newEmitter The new emitter to use
  57742. * @returns the cloned particle system
  57743. */
  57744. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57745. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57746. BABYLON.Tools.DeepCopy(this, result);
  57747. if (newEmitter === undefined) {
  57748. newEmitter = this.emitter;
  57749. }
  57750. result.emitter = newEmitter;
  57751. if (this.particleTexture) {
  57752. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57753. }
  57754. return result;
  57755. };
  57756. /**
  57757. * Serializes the particle system to a JSON object.
  57758. * @returns the JSON object
  57759. */
  57760. GPUParticleSystem.prototype.serialize = function () {
  57761. var serializationObject = {};
  57762. serializationObject.name = this.name;
  57763. serializationObject.id = this.id;
  57764. // Emitter
  57765. if (this.emitter.position) {
  57766. var emitterMesh = this.emitter;
  57767. serializationObject.emitterId = emitterMesh.id;
  57768. }
  57769. else {
  57770. var emitterPosition = this.emitter;
  57771. serializationObject.emitter = emitterPosition.asArray();
  57772. }
  57773. serializationObject.capacity = this.getCapacity();
  57774. if (this.particleTexture) {
  57775. serializationObject.textureName = this.particleTexture.name;
  57776. }
  57777. // Animations
  57778. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57779. // Particle system
  57780. serializationObject.activeParticleCount = this.activeParticleCount;
  57781. serializationObject.randomTextureSize = this._randomTextureSize;
  57782. serializationObject.minSize = this.minSize;
  57783. serializationObject.maxSize = this.maxSize;
  57784. serializationObject.minEmitPower = this.minEmitPower;
  57785. serializationObject.maxEmitPower = this.maxEmitPower;
  57786. serializationObject.minLifeTime = this.minLifeTime;
  57787. serializationObject.maxLifeTime = this.maxLifeTime;
  57788. serializationObject.emitRate = this.emitRate;
  57789. serializationObject.gravity = this.gravity.asArray();
  57790. serializationObject.color1 = this.color1.asArray();
  57791. serializationObject.color2 = this.color2.asArray();
  57792. serializationObject.colorDead = this.colorDead.asArray();
  57793. serializationObject.updateSpeed = this.updateSpeed;
  57794. serializationObject.targetStopDuration = this.targetStopDuration;
  57795. serializationObject.blendMode = this.blendMode;
  57796. // Emitter
  57797. if (this.particleEmitterType) {
  57798. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57799. }
  57800. return serializationObject;
  57801. };
  57802. /**
  57803. * Parses a JSON object to create a GPU particle system.
  57804. * @param parsedParticleSystem The JSON object to parse
  57805. * @param scene The scene to create the particle system in
  57806. * @param rootUrl The root url to use to load external dependencies like texture
  57807. * @returns the parsed GPU particle system
  57808. */
  57809. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57810. var name = parsedParticleSystem.name;
  57811. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57812. if (parsedParticleSystem.id) {
  57813. particleSystem.id = parsedParticleSystem.id;
  57814. }
  57815. // Texture
  57816. if (parsedParticleSystem.textureName) {
  57817. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57818. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57819. }
  57820. // Emitter
  57821. if (parsedParticleSystem.emitterId) {
  57822. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57823. }
  57824. else {
  57825. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57826. }
  57827. // Animations
  57828. if (parsedParticleSystem.animations) {
  57829. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57830. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57831. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57832. }
  57833. }
  57834. // Particle system
  57835. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57836. particleSystem.minSize = parsedParticleSystem.minSize;
  57837. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57838. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57839. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57840. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57841. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57842. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57843. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57844. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57845. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57846. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57847. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57848. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57849. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57850. // Emitter
  57851. if (parsedParticleSystem.particleEmitterType) {
  57852. var emitterType = void 0;
  57853. switch (parsedParticleSystem.particleEmitterType.type) {
  57854. case "SphereEmitter":
  57855. emitterType = new BABYLON.SphereParticleEmitter();
  57856. break;
  57857. case "SphereDirectedParticleEmitter":
  57858. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57859. break;
  57860. case "ConeEmitter":
  57861. emitterType = new BABYLON.ConeParticleEmitter();
  57862. break;
  57863. case "BoxEmitter":
  57864. default:
  57865. emitterType = new BABYLON.BoxParticleEmitter();
  57866. break;
  57867. }
  57868. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57869. particleSystem.particleEmitterType = emitterType;
  57870. }
  57871. return particleSystem;
  57872. };
  57873. return GPUParticleSystem;
  57874. }());
  57875. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57876. })(BABYLON || (BABYLON = {}));
  57877. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57878. var BABYLON;
  57879. (function (BABYLON) {
  57880. /**
  57881. * Represents one particle of a solid particle system.
  57882. */
  57883. var SolidParticle = /** @class */ (function () {
  57884. /**
  57885. * Creates a Solid Particle object.
  57886. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57887. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57888. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57889. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57890. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57891. * @param shapeId (integer) is the model shape identifier in the SPS.
  57892. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57893. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57894. */
  57895. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57896. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57897. /**
  57898. * particle global index
  57899. */
  57900. this.idx = 0;
  57901. /**
  57902. * The color of the particle
  57903. */
  57904. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57905. /**
  57906. * The world space position of the particle.
  57907. */
  57908. this.position = BABYLON.Vector3.Zero();
  57909. /**
  57910. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57911. */
  57912. this.rotation = BABYLON.Vector3.Zero();
  57913. /**
  57914. * The scaling of the particle.
  57915. */
  57916. this.scaling = BABYLON.Vector3.One();
  57917. /**
  57918. * The uvs of the particle.
  57919. */
  57920. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57921. /**
  57922. * The current speed of the particle.
  57923. */
  57924. this.velocity = BABYLON.Vector3.Zero();
  57925. /**
  57926. * The pivot point in the particle local space.
  57927. */
  57928. this.pivot = BABYLON.Vector3.Zero();
  57929. /**
  57930. * Must the particle be translated from its pivot point in its local space ?
  57931. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57932. * Default : false
  57933. */
  57934. this.translateFromPivot = false;
  57935. /**
  57936. * Is the particle active or not ?
  57937. */
  57938. this.alive = true;
  57939. /**
  57940. * Is the particle visible or not ?
  57941. */
  57942. this.isVisible = true;
  57943. /**
  57944. * Index of this particle in the global "positions" array (Internal use)
  57945. */
  57946. this._pos = 0;
  57947. /**
  57948. * Index of this particle in the global "indices" array (Internal use)
  57949. */
  57950. this._ind = 0;
  57951. /**
  57952. * ModelShape id of this particle
  57953. */
  57954. this.shapeId = 0;
  57955. /**
  57956. * Index of the particle in its shape id (Internal use)
  57957. */
  57958. this.idxInShape = 0;
  57959. /**
  57960. * Still set as invisible in order to skip useless computations (Internal use)
  57961. */
  57962. this._stillInvisible = false;
  57963. /**
  57964. * Last computed particle rotation matrix
  57965. */
  57966. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57967. /**
  57968. * Parent particle Id, if any.
  57969. * Default null.
  57970. */
  57971. this.parentId = null;
  57972. /**
  57973. * Internal global position in the SPS.
  57974. */
  57975. this._globalPosition = BABYLON.Vector3.Zero();
  57976. this.idx = particleIndex;
  57977. this._pos = positionIndex;
  57978. this._ind = indiceIndex;
  57979. this._model = model;
  57980. this.shapeId = shapeId;
  57981. this.idxInShape = idxInShape;
  57982. this._sps = sps;
  57983. if (modelBoundingInfo) {
  57984. this._modelBoundingInfo = modelBoundingInfo;
  57985. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57986. }
  57987. }
  57988. Object.defineProperty(SolidParticle.prototype, "scale", {
  57989. /**
  57990. * Legacy support, changed scale to scaling
  57991. */
  57992. get: function () {
  57993. return this.scaling;
  57994. },
  57995. /**
  57996. * Legacy support, changed scale to scaling
  57997. */
  57998. set: function (scale) {
  57999. this.scaling = scale;
  58000. },
  58001. enumerable: true,
  58002. configurable: true
  58003. });
  58004. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58005. /**
  58006. * Legacy support, changed quaternion to rotationQuaternion
  58007. */
  58008. get: function () {
  58009. return this.rotationQuaternion;
  58010. },
  58011. /**
  58012. * Legacy support, changed quaternion to rotationQuaternion
  58013. */
  58014. set: function (q) {
  58015. this.rotationQuaternion = q;
  58016. },
  58017. enumerable: true,
  58018. configurable: true
  58019. });
  58020. /**
  58021. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58022. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58023. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58024. * @returns true if it intersects
  58025. */
  58026. SolidParticle.prototype.intersectsMesh = function (target) {
  58027. if (!this._boundingInfo || !target._boundingInfo) {
  58028. return false;
  58029. }
  58030. if (this._sps._bSphereOnly) {
  58031. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58032. }
  58033. return this._boundingInfo.intersects(target._boundingInfo, false);
  58034. };
  58035. return SolidParticle;
  58036. }());
  58037. BABYLON.SolidParticle = SolidParticle;
  58038. /**
  58039. * Represents the shape of the model used by one particle of a solid particle system.
  58040. * SPS internal tool, don't use it manually.
  58041. */
  58042. var ModelShape = /** @class */ (function () {
  58043. /**
  58044. * 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.
  58045. * SPS internal tool, don't use it manually.
  58046. * @hidden
  58047. */
  58048. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58049. /**
  58050. * length of the shape in the model indices array (internal use)
  58051. */
  58052. this._indicesLength = 0;
  58053. this.shapeID = id;
  58054. this._shape = shape;
  58055. this._indicesLength = indicesLength;
  58056. this._shapeUV = shapeUV;
  58057. this._positionFunction = posFunction;
  58058. this._vertexFunction = vtxFunction;
  58059. }
  58060. return ModelShape;
  58061. }());
  58062. BABYLON.ModelShape = ModelShape;
  58063. /**
  58064. * Represents a Depth Sorted Particle in the solid particle system.
  58065. */
  58066. var DepthSortedParticle = /** @class */ (function () {
  58067. function DepthSortedParticle() {
  58068. /**
  58069. * Index of the particle in the "indices" array
  58070. */
  58071. this.ind = 0;
  58072. /**
  58073. * Length of the particle shape in the "indices" array
  58074. */
  58075. this.indicesLength = 0;
  58076. /**
  58077. * Squared distance from the particle to the camera
  58078. */
  58079. this.sqDistance = 0.0;
  58080. }
  58081. return DepthSortedParticle;
  58082. }());
  58083. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58084. })(BABYLON || (BABYLON = {}));
  58085. //# sourceMappingURL=babylon.solidParticle.js.map
  58086. var BABYLON;
  58087. (function (BABYLON) {
  58088. /**
  58089. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58090. *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.
  58091. * The SPS is also a particle system. It provides some methods to manage the particles.
  58092. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58093. *
  58094. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58095. */
  58096. var SolidParticleSystem = /** @class */ (function () {
  58097. /**
  58098. * Creates a SPS (Solid Particle System) object.
  58099. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58100. * @param scene (Scene) is the scene in which the SPS is added.
  58101. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58102. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58103. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58104. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58105. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58106. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58107. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58108. */
  58109. function SolidParticleSystem(name, scene, options) {
  58110. /**
  58111. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58112. * Example : var p = SPS.particles[i];
  58113. */
  58114. this.particles = new Array();
  58115. /**
  58116. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58117. */
  58118. this.nbParticles = 0;
  58119. /**
  58120. * If the particles must ever face the camera (default false). Useful for planar particles.
  58121. */
  58122. this.billboard = false;
  58123. /**
  58124. * Recompute normals when adding a shape
  58125. */
  58126. this.recomputeNormals = true;
  58127. /**
  58128. * This a counter ofr your own usage. It's not set by any SPS functions.
  58129. */
  58130. this.counter = 0;
  58131. /**
  58132. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58133. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58134. */
  58135. this.vars = {};
  58136. /**
  58137. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58138. */
  58139. this._bSphereOnly = false;
  58140. /**
  58141. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58142. */
  58143. this._bSphereRadiusFactor = 1.0;
  58144. this._positions = new Array();
  58145. this._indices = new Array();
  58146. this._normals = new Array();
  58147. this._colors = new Array();
  58148. this._uvs = new Array();
  58149. this._index = 0; // indices index
  58150. this._updatable = true;
  58151. this._pickable = false;
  58152. this._isVisibilityBoxLocked = false;
  58153. this._alwaysVisible = false;
  58154. this._depthSort = false;
  58155. this._shapeCounter = 0;
  58156. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58157. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58158. this._computeParticleColor = true;
  58159. this._computeParticleTexture = true;
  58160. this._computeParticleRotation = true;
  58161. this._computeParticleVertex = false;
  58162. this._computeBoundingBox = false;
  58163. this._depthSortParticles = true;
  58164. this._cam_axisZ = BABYLON.Vector3.Zero();
  58165. this._cam_axisY = BABYLON.Vector3.Zero();
  58166. this._cam_axisX = BABYLON.Vector3.Zero();
  58167. this._axisZ = BABYLON.Axis.Z;
  58168. this._camDir = BABYLON.Vector3.Zero();
  58169. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58170. this._rotMatrix = new BABYLON.Matrix();
  58171. this._invertMatrix = new BABYLON.Matrix();
  58172. this._rotated = BABYLON.Vector3.Zero();
  58173. this._quaternion = new BABYLON.Quaternion();
  58174. this._vertex = BABYLON.Vector3.Zero();
  58175. this._normal = BABYLON.Vector3.Zero();
  58176. this._yaw = 0.0;
  58177. this._pitch = 0.0;
  58178. this._roll = 0.0;
  58179. this._halfroll = 0.0;
  58180. this._halfpitch = 0.0;
  58181. this._halfyaw = 0.0;
  58182. this._sinRoll = 0.0;
  58183. this._cosRoll = 0.0;
  58184. this._sinPitch = 0.0;
  58185. this._cosPitch = 0.0;
  58186. this._sinYaw = 0.0;
  58187. this._cosYaw = 0.0;
  58188. this._mustUnrotateFixedNormals = false;
  58189. this._minimum = BABYLON.Vector3.Zero();
  58190. this._maximum = BABYLON.Vector3.Zero();
  58191. this._minBbox = BABYLON.Vector3.Zero();
  58192. this._maxBbox = BABYLON.Vector3.Zero();
  58193. this._particlesIntersect = false;
  58194. this._depthSortFunction = function (p1, p2) {
  58195. return (p2.sqDistance - p1.sqDistance);
  58196. };
  58197. this._needs32Bits = false;
  58198. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58199. this._scaledPivot = BABYLON.Vector3.Zero();
  58200. this._particleHasParent = false;
  58201. this.name = name;
  58202. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58203. this._camera = scene.activeCamera;
  58204. this._pickable = options ? options.isPickable : false;
  58205. this._depthSort = options ? options.enableDepthSort : false;
  58206. this._particlesIntersect = options ? options.particleIntersection : false;
  58207. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58208. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58209. if (options && options.updatable) {
  58210. this._updatable = options.updatable;
  58211. }
  58212. else {
  58213. this._updatable = true;
  58214. }
  58215. if (this._pickable) {
  58216. this.pickedParticles = [];
  58217. }
  58218. if (this._depthSort) {
  58219. this.depthSortedParticles = [];
  58220. }
  58221. }
  58222. /**
  58223. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58224. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58225. * @returns the created mesh
  58226. */
  58227. SolidParticleSystem.prototype.buildMesh = function () {
  58228. if (this.nbParticles === 0) {
  58229. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58230. this.addShape(triangle, 1);
  58231. triangle.dispose();
  58232. }
  58233. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58234. this._positions32 = new Float32Array(this._positions);
  58235. this._uvs32 = new Float32Array(this._uvs);
  58236. this._colors32 = new Float32Array(this._colors);
  58237. if (this.recomputeNormals) {
  58238. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58239. }
  58240. this._normals32 = new Float32Array(this._normals);
  58241. this._fixedNormal32 = new Float32Array(this._normals);
  58242. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58243. this._unrotateFixedNormals();
  58244. }
  58245. var vertexData = new BABYLON.VertexData();
  58246. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58247. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58248. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58249. if (this._uvs32.length > 0) {
  58250. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58251. }
  58252. if (this._colors32.length > 0) {
  58253. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58254. }
  58255. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58256. vertexData.applyToMesh(mesh, this._updatable);
  58257. this.mesh = mesh;
  58258. this.mesh.isPickable = this._pickable;
  58259. // free memory
  58260. if (!this._depthSort) {
  58261. this._indices = null;
  58262. }
  58263. this._positions = null;
  58264. this._normals = null;
  58265. this._uvs = null;
  58266. this._colors = null;
  58267. if (!this._updatable) {
  58268. this.particles.length = 0;
  58269. }
  58270. return mesh;
  58271. };
  58272. /**
  58273. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58274. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58275. * Thus the particles generated from `digest()` have their property `position` set yet.
  58276. * @param mesh ( Mesh ) is the mesh to be digested
  58277. * @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
  58278. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58279. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58280. * @returns the current SPS
  58281. */
  58282. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58283. var size = (options && options.facetNb) || 1;
  58284. var number = (options && options.number) || 0;
  58285. var delta = (options && options.delta) || 0;
  58286. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58287. var meshInd = mesh.getIndices();
  58288. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58289. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58290. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58291. var f = 0; // facet counter
  58292. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58293. // compute size from number
  58294. if (number) {
  58295. number = (number > totalFacets) ? totalFacets : number;
  58296. size = Math.round(totalFacets / number);
  58297. delta = 0;
  58298. }
  58299. else {
  58300. size = (size > totalFacets) ? totalFacets : size;
  58301. }
  58302. var facetPos = []; // submesh positions
  58303. var facetInd = []; // submesh indices
  58304. var facetUV = []; // submesh UV
  58305. var facetCol = []; // submesh colors
  58306. var barycenter = BABYLON.Vector3.Zero();
  58307. var sizeO = size;
  58308. while (f < totalFacets) {
  58309. size = sizeO + Math.floor((1 + delta) * Math.random());
  58310. if (f > totalFacets - size) {
  58311. size = totalFacets - f;
  58312. }
  58313. // reset temp arrays
  58314. facetPos.length = 0;
  58315. facetInd.length = 0;
  58316. facetUV.length = 0;
  58317. facetCol.length = 0;
  58318. // iterate over "size" facets
  58319. var fi = 0;
  58320. for (var j = f * 3; j < (f + size) * 3; j++) {
  58321. facetInd.push(fi);
  58322. var i = meshInd[j];
  58323. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58324. if (meshUV) {
  58325. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58326. }
  58327. if (meshCol) {
  58328. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58329. }
  58330. fi++;
  58331. }
  58332. // create a model shape for each single particle
  58333. var idx = this.nbParticles;
  58334. var shape = this._posToShape(facetPos);
  58335. var shapeUV = this._uvsToShapeUV(facetUV);
  58336. // compute the barycenter of the shape
  58337. var v;
  58338. for (v = 0; v < shape.length; v++) {
  58339. barycenter.addInPlace(shape[v]);
  58340. }
  58341. barycenter.scaleInPlace(1 / shape.length);
  58342. // shift the shape from its barycenter to the origin
  58343. for (v = 0; v < shape.length; v++) {
  58344. shape[v].subtractInPlace(barycenter);
  58345. }
  58346. var bInfo;
  58347. if (this._particlesIntersect) {
  58348. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58349. }
  58350. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58351. // add the particle in the SPS
  58352. var currentPos = this._positions.length;
  58353. var currentInd = this._indices.length;
  58354. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58355. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58356. // initialize the particle position
  58357. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58358. this._index += shape.length;
  58359. idx++;
  58360. this.nbParticles++;
  58361. this._shapeCounter++;
  58362. f += size;
  58363. }
  58364. return this;
  58365. };
  58366. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58367. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58368. var index = 0;
  58369. var idx = 0;
  58370. for (var p = 0; p < this.particles.length; p++) {
  58371. this._particle = this.particles[p];
  58372. this._shape = this._particle._model._shape;
  58373. if (this._particle.rotationQuaternion) {
  58374. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58375. }
  58376. else {
  58377. this._yaw = this._particle.rotation.y;
  58378. this._pitch = this._particle.rotation.x;
  58379. this._roll = this._particle.rotation.z;
  58380. this._quaternionRotationYPR();
  58381. }
  58382. this._quaternionToRotationMatrix();
  58383. this._rotMatrix.invertToRef(this._invertMatrix);
  58384. for (var pt = 0; pt < this._shape.length; pt++) {
  58385. idx = index + pt * 3;
  58386. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58387. this._fixedNormal32[idx] = this._normal.x;
  58388. this._fixedNormal32[idx + 1] = this._normal.y;
  58389. this._fixedNormal32[idx + 2] = this._normal.z;
  58390. }
  58391. index = idx + 3;
  58392. }
  58393. };
  58394. //reset copy
  58395. SolidParticleSystem.prototype._resetCopy = function () {
  58396. this._copy.position.x = 0;
  58397. this._copy.position.y = 0;
  58398. this._copy.position.z = 0;
  58399. this._copy.rotation.x = 0;
  58400. this._copy.rotation.y = 0;
  58401. this._copy.rotation.z = 0;
  58402. this._copy.rotationQuaternion = null;
  58403. this._copy.scaling.x = 1.0;
  58404. this._copy.scaling.y = 1.0;
  58405. this._copy.scaling.z = 1.0;
  58406. this._copy.uvs.x = 0;
  58407. this._copy.uvs.y = 0;
  58408. this._copy.uvs.z = 1.0;
  58409. this._copy.uvs.w = 1.0;
  58410. this._copy.color = null;
  58411. this._copy.translateFromPivot = false;
  58412. };
  58413. // _meshBuilder : inserts the shape model in the global SPS mesh
  58414. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58415. var i;
  58416. var u = 0;
  58417. var c = 0;
  58418. var n = 0;
  58419. this._resetCopy();
  58420. if (options && options.positionFunction) { // call to custom positionFunction
  58421. options.positionFunction(this._copy, idx, idxInShape);
  58422. this._mustUnrotateFixedNormals = true;
  58423. }
  58424. if (this._copy.rotationQuaternion) {
  58425. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58426. }
  58427. else {
  58428. this._yaw = this._copy.rotation.y;
  58429. this._pitch = this._copy.rotation.x;
  58430. this._roll = this._copy.rotation.z;
  58431. this._quaternionRotationYPR();
  58432. }
  58433. this._quaternionToRotationMatrix();
  58434. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58435. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58436. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58437. if (this._copy.translateFromPivot) {
  58438. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58439. }
  58440. else {
  58441. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58442. }
  58443. for (i = 0; i < shape.length; i++) {
  58444. this._vertex.x = shape[i].x;
  58445. this._vertex.y = shape[i].y;
  58446. this._vertex.z = shape[i].z;
  58447. if (options && options.vertexFunction) {
  58448. options.vertexFunction(this._copy, this._vertex, i);
  58449. }
  58450. this._vertex.x *= this._copy.scaling.x;
  58451. this._vertex.y *= this._copy.scaling.y;
  58452. this._vertex.z *= this._copy.scaling.z;
  58453. this._vertex.x -= this._scaledPivot.x;
  58454. this._vertex.y -= this._scaledPivot.y;
  58455. this._vertex.z -= this._scaledPivot.z;
  58456. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58457. this._rotated.addInPlace(this._pivotBackTranslation);
  58458. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58459. if (meshUV) {
  58460. 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);
  58461. u += 2;
  58462. }
  58463. if (this._copy.color) {
  58464. this._color = this._copy.color;
  58465. }
  58466. else if (meshCol && meshCol[c] !== undefined) {
  58467. this._color.r = meshCol[c];
  58468. this._color.g = meshCol[c + 1];
  58469. this._color.b = meshCol[c + 2];
  58470. this._color.a = meshCol[c + 3];
  58471. }
  58472. else {
  58473. this._color.r = 1.0;
  58474. this._color.g = 1.0;
  58475. this._color.b = 1.0;
  58476. this._color.a = 1.0;
  58477. }
  58478. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58479. c += 4;
  58480. if (!this.recomputeNormals && meshNor) {
  58481. this._normal.x = meshNor[n];
  58482. this._normal.y = meshNor[n + 1];
  58483. this._normal.z = meshNor[n + 2];
  58484. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58485. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58486. n += 3;
  58487. }
  58488. }
  58489. for (i = 0; i < meshInd.length; i++) {
  58490. var current_ind = p + meshInd[i];
  58491. indices.push(current_ind);
  58492. if (current_ind > 65535) {
  58493. this._needs32Bits = true;
  58494. }
  58495. }
  58496. if (this._pickable) {
  58497. var nbfaces = meshInd.length / 3;
  58498. for (i = 0; i < nbfaces; i++) {
  58499. this.pickedParticles.push({ idx: idx, faceId: i });
  58500. }
  58501. }
  58502. if (this._depthSort) {
  58503. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58504. }
  58505. return this._copy;
  58506. };
  58507. // returns a shape array from positions array
  58508. SolidParticleSystem.prototype._posToShape = function (positions) {
  58509. var shape = [];
  58510. for (var i = 0; i < positions.length; i += 3) {
  58511. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58512. }
  58513. return shape;
  58514. };
  58515. // returns a shapeUV array from a Vector4 uvs
  58516. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58517. var shapeUV = [];
  58518. if (uvs) {
  58519. for (var i = 0; i < uvs.length; i++)
  58520. shapeUV.push(uvs[i]);
  58521. }
  58522. return shapeUV;
  58523. };
  58524. // adds a new particle object in the particles array
  58525. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58526. if (bInfo === void 0) { bInfo = null; }
  58527. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58528. this.particles.push(sp);
  58529. return sp;
  58530. };
  58531. /**
  58532. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58533. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58534. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58535. * @param nb (positive integer) the number of particles to be created from this model
  58536. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58537. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58538. * @returns the number of shapes in the system
  58539. */
  58540. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58541. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58542. var meshInd = mesh.getIndices();
  58543. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58544. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58545. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58546. var bbInfo;
  58547. if (this._particlesIntersect) {
  58548. bbInfo = mesh.getBoundingInfo();
  58549. }
  58550. var shape = this._posToShape(meshPos);
  58551. var shapeUV = this._uvsToShapeUV(meshUV);
  58552. var posfunc = options ? options.positionFunction : null;
  58553. var vtxfunc = options ? options.vertexFunction : null;
  58554. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58555. // particles
  58556. var sp;
  58557. var currentCopy;
  58558. var idx = this.nbParticles;
  58559. for (var i = 0; i < nb; i++) {
  58560. var currentPos = this._positions.length;
  58561. var currentInd = this._indices.length;
  58562. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58563. if (this._updatable) {
  58564. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58565. sp.position.copyFrom(currentCopy.position);
  58566. sp.rotation.copyFrom(currentCopy.rotation);
  58567. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58568. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58569. }
  58570. if (currentCopy.color && sp.color) {
  58571. sp.color.copyFrom(currentCopy.color);
  58572. }
  58573. sp.scaling.copyFrom(currentCopy.scaling);
  58574. sp.uvs.copyFrom(currentCopy.uvs);
  58575. }
  58576. this._index += shape.length;
  58577. idx++;
  58578. }
  58579. this.nbParticles += nb;
  58580. this._shapeCounter++;
  58581. return this._shapeCounter - 1;
  58582. };
  58583. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58584. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58585. this._resetCopy();
  58586. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58587. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58588. }
  58589. if (this._copy.rotationQuaternion) {
  58590. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58591. }
  58592. else {
  58593. this._yaw = this._copy.rotation.y;
  58594. this._pitch = this._copy.rotation.x;
  58595. this._roll = this._copy.rotation.z;
  58596. this._quaternionRotationYPR();
  58597. }
  58598. this._quaternionToRotationMatrix();
  58599. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58600. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58601. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58602. if (this._copy.translateFromPivot) {
  58603. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58604. }
  58605. else {
  58606. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58607. }
  58608. this._shape = particle._model._shape;
  58609. for (var pt = 0; pt < this._shape.length; pt++) {
  58610. this._vertex.x = this._shape[pt].x;
  58611. this._vertex.y = this._shape[pt].y;
  58612. this._vertex.z = this._shape[pt].z;
  58613. if (particle._model._vertexFunction) {
  58614. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58615. }
  58616. this._vertex.x *= this._copy.scaling.x;
  58617. this._vertex.y *= this._copy.scaling.y;
  58618. this._vertex.z *= this._copy.scaling.z;
  58619. this._vertex.x -= this._scaledPivot.x;
  58620. this._vertex.y -= this._scaledPivot.y;
  58621. this._vertex.z -= this._scaledPivot.z;
  58622. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58623. this._rotated.addInPlace(this._pivotBackTranslation);
  58624. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58625. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58626. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58627. }
  58628. particle.position.x = 0.0;
  58629. particle.position.y = 0.0;
  58630. particle.position.z = 0.0;
  58631. particle.rotation.x = 0.0;
  58632. particle.rotation.y = 0.0;
  58633. particle.rotation.z = 0.0;
  58634. particle.rotationQuaternion = null;
  58635. particle.scaling.x = 1.0;
  58636. particle.scaling.y = 1.0;
  58637. particle.scaling.z = 1.0;
  58638. particle.uvs.x = 0.0;
  58639. particle.uvs.y = 0.0;
  58640. particle.uvs.z = 1.0;
  58641. particle.uvs.w = 1.0;
  58642. particle.pivot.x = 0.0;
  58643. particle.pivot.y = 0.0;
  58644. particle.pivot.z = 0.0;
  58645. particle.translateFromPivot = false;
  58646. particle.parentId = null;
  58647. };
  58648. /**
  58649. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58650. * @returns the SPS.
  58651. */
  58652. SolidParticleSystem.prototype.rebuildMesh = function () {
  58653. for (var p = 0; p < this.particles.length; p++) {
  58654. this._rebuildParticle(this.particles[p]);
  58655. }
  58656. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58657. return this;
  58658. };
  58659. /**
  58660. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58661. * This method calls `updateParticle()` for each particle of the SPS.
  58662. * For an animated SPS, it is usually called within the render loop.
  58663. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58664. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58665. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58666. * @returns the SPS.
  58667. */
  58668. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58669. if (start === void 0) { start = 0; }
  58670. if (end === void 0) { end = this.nbParticles - 1; }
  58671. if (update === void 0) { update = true; }
  58672. if (!this._updatable) {
  58673. return this;
  58674. }
  58675. // custom beforeUpdate
  58676. this.beforeUpdateParticles(start, end, update);
  58677. this._cam_axisX.x = 1.0;
  58678. this._cam_axisX.y = 0.0;
  58679. this._cam_axisX.z = 0.0;
  58680. this._cam_axisY.x = 0.0;
  58681. this._cam_axisY.y = 1.0;
  58682. this._cam_axisY.z = 0.0;
  58683. this._cam_axisZ.x = 0.0;
  58684. this._cam_axisZ.y = 0.0;
  58685. this._cam_axisZ.z = 1.0;
  58686. // cases when the World Matrix is to be computed first
  58687. if (this.billboard || this._depthSort) {
  58688. this.mesh.computeWorldMatrix(true);
  58689. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58690. }
  58691. // if the particles will always face the camera
  58692. if (this.billboard) {
  58693. // compute the camera position and un-rotate it by the current mesh rotation
  58694. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58695. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58696. this._cam_axisZ.normalize();
  58697. // same for camera up vector extracted from the cam view matrix
  58698. var view = this._camera.getViewMatrix(true);
  58699. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58700. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58701. this._cam_axisY.normalize();
  58702. this._cam_axisX.normalize();
  58703. }
  58704. // if depthSort, compute the camera global position in the mesh local system
  58705. if (this._depthSort) {
  58706. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58707. }
  58708. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58709. var idx = 0; // current position index in the global array positions32
  58710. var index = 0; // position start index in the global array positions32 of the current particle
  58711. var colidx = 0; // current color index in the global array colors32
  58712. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58713. var uvidx = 0; // current uv index in the global array uvs32
  58714. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58715. var pt = 0; // current index in the particle model shape
  58716. if (this.mesh.isFacetDataEnabled) {
  58717. this._computeBoundingBox = true;
  58718. }
  58719. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58720. if (this._computeBoundingBox) {
  58721. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58722. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58723. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58724. }
  58725. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58726. if (this.mesh._boundingInfo) {
  58727. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58728. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58729. }
  58730. }
  58731. }
  58732. // particle loop
  58733. index = this.particles[start]._pos;
  58734. var vpos = (index / 3) | 0;
  58735. colorIndex = vpos * 4;
  58736. uvIndex = vpos * 2;
  58737. for (var p = start; p <= end; p++) {
  58738. this._particle = this.particles[p];
  58739. this._shape = this._particle._model._shape;
  58740. this._shapeUV = this._particle._model._shapeUV;
  58741. // call to custom user function to update the particle properties
  58742. this.updateParticle(this._particle);
  58743. // camera-particle distance for depth sorting
  58744. if (this._depthSort && this._depthSortParticles) {
  58745. var dsp = this.depthSortedParticles[p];
  58746. dsp.ind = this._particle._ind;
  58747. dsp.indicesLength = this._particle._model._indicesLength;
  58748. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58749. }
  58750. // skip the computations for inactive or already invisible particles
  58751. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58752. // increment indexes for the next particle
  58753. pt = this._shape.length;
  58754. index += pt * 3;
  58755. colorIndex += pt * 4;
  58756. uvIndex += pt * 2;
  58757. continue;
  58758. }
  58759. if (this._particle.isVisible) {
  58760. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58761. this._particleHasParent = (this._particle.parentId !== null);
  58762. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58763. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58764. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58765. // particle rotation matrix
  58766. if (this.billboard) {
  58767. this._particle.rotation.x = 0.0;
  58768. this._particle.rotation.y = 0.0;
  58769. }
  58770. if (this._computeParticleRotation || this.billboard) {
  58771. if (this._particle.rotationQuaternion) {
  58772. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58773. }
  58774. else {
  58775. this._yaw = this._particle.rotation.y;
  58776. this._pitch = this._particle.rotation.x;
  58777. this._roll = this._particle.rotation.z;
  58778. this._quaternionRotationYPR();
  58779. }
  58780. this._quaternionToRotationMatrix();
  58781. }
  58782. if (this._particleHasParent) {
  58783. this._parent = this.particles[this._particle.parentId];
  58784. 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];
  58785. 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];
  58786. 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];
  58787. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58788. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58789. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58790. if (this._computeParticleRotation || this.billboard) {
  58791. 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];
  58792. 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];
  58793. 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];
  58794. 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];
  58795. 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];
  58796. 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];
  58797. 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];
  58798. 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];
  58799. 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];
  58800. }
  58801. }
  58802. else {
  58803. this._particle._globalPosition.x = this._particle.position.x;
  58804. this._particle._globalPosition.y = this._particle.position.y;
  58805. this._particle._globalPosition.z = this._particle.position.z;
  58806. if (this._computeParticleRotation || this.billboard) {
  58807. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58808. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58809. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58810. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58811. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58812. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58813. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58814. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58815. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58816. }
  58817. }
  58818. if (this._particle.translateFromPivot) {
  58819. this._pivotBackTranslation.x = 0.0;
  58820. this._pivotBackTranslation.y = 0.0;
  58821. this._pivotBackTranslation.z = 0.0;
  58822. }
  58823. else {
  58824. this._pivotBackTranslation.x = this._scaledPivot.x;
  58825. this._pivotBackTranslation.y = this._scaledPivot.y;
  58826. this._pivotBackTranslation.z = this._scaledPivot.z;
  58827. }
  58828. // particle vertex loop
  58829. for (pt = 0; pt < this._shape.length; pt++) {
  58830. idx = index + pt * 3;
  58831. colidx = colorIndex + pt * 4;
  58832. uvidx = uvIndex + pt * 2;
  58833. this._vertex.x = this._shape[pt].x;
  58834. this._vertex.y = this._shape[pt].y;
  58835. this._vertex.z = this._shape[pt].z;
  58836. if (this._computeParticleVertex) {
  58837. this.updateParticleVertex(this._particle, this._vertex, pt);
  58838. }
  58839. // positions
  58840. this._vertex.x *= this._particle.scaling.x;
  58841. this._vertex.y *= this._particle.scaling.y;
  58842. this._vertex.z *= this._particle.scaling.z;
  58843. this._vertex.x -= this._scaledPivot.x;
  58844. this._vertex.y -= this._scaledPivot.y;
  58845. this._vertex.z -= this._scaledPivot.z;
  58846. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58847. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58848. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58849. this._rotated.x += this._pivotBackTranslation.x;
  58850. this._rotated.y += this._pivotBackTranslation.y;
  58851. this._rotated.z += this._pivotBackTranslation.z;
  58852. 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;
  58853. 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;
  58854. 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;
  58855. if (this._computeBoundingBox) {
  58856. if (this._positions32[idx] < this._minimum.x) {
  58857. this._minimum.x = this._positions32[idx];
  58858. }
  58859. if (this._positions32[idx] > this._maximum.x) {
  58860. this._maximum.x = this._positions32[idx];
  58861. }
  58862. if (this._positions32[idx + 1] < this._minimum.y) {
  58863. this._minimum.y = this._positions32[idx + 1];
  58864. }
  58865. if (this._positions32[idx + 1] > this._maximum.y) {
  58866. this._maximum.y = this._positions32[idx + 1];
  58867. }
  58868. if (this._positions32[idx + 2] < this._minimum.z) {
  58869. this._minimum.z = this._positions32[idx + 2];
  58870. }
  58871. if (this._positions32[idx + 2] > this._maximum.z) {
  58872. this._maximum.z = this._positions32[idx + 2];
  58873. }
  58874. }
  58875. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58876. if (!this._computeParticleVertex) {
  58877. this._normal.x = this._fixedNormal32[idx];
  58878. this._normal.y = this._fixedNormal32[idx + 1];
  58879. this._normal.z = this._fixedNormal32[idx + 2];
  58880. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58881. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58882. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58883. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58884. 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;
  58885. 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;
  58886. }
  58887. if (this._computeParticleColor && this._particle.color) {
  58888. this._colors32[colidx] = this._particle.color.r;
  58889. this._colors32[colidx + 1] = this._particle.color.g;
  58890. this._colors32[colidx + 2] = this._particle.color.b;
  58891. this._colors32[colidx + 3] = this._particle.color.a;
  58892. }
  58893. if (this._computeParticleTexture) {
  58894. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58895. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58896. }
  58897. }
  58898. }
  58899. // particle just set invisible : scaled to zero and positioned at the origin
  58900. else {
  58901. this._particle._stillInvisible = true; // mark the particle as invisible
  58902. for (pt = 0; pt < this._shape.length; pt++) {
  58903. idx = index + pt * 3;
  58904. colidx = colorIndex + pt * 4;
  58905. uvidx = uvIndex + pt * 2;
  58906. this._positions32[idx] = 0.0;
  58907. this._positions32[idx + 1] = 0.0;
  58908. this._positions32[idx + 2] = 0.0;
  58909. this._normals32[idx] = 0.0;
  58910. this._normals32[idx + 1] = 0.0;
  58911. this._normals32[idx + 2] = 0.0;
  58912. if (this._computeParticleColor && this._particle.color) {
  58913. this._colors32[colidx] = this._particle.color.r;
  58914. this._colors32[colidx + 1] = this._particle.color.g;
  58915. this._colors32[colidx + 2] = this._particle.color.b;
  58916. this._colors32[colidx + 3] = this._particle.color.a;
  58917. }
  58918. if (this._computeParticleTexture) {
  58919. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58920. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58921. }
  58922. }
  58923. }
  58924. // if the particle intersections must be computed : update the bbInfo
  58925. if (this._particlesIntersect) {
  58926. var bInfo = this._particle._boundingInfo;
  58927. var bBox = bInfo.boundingBox;
  58928. var bSphere = bInfo.boundingSphere;
  58929. if (!this._bSphereOnly) {
  58930. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58931. for (var b = 0; b < bBox.vectors.length; b++) {
  58932. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58933. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58934. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58935. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58936. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58937. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58938. 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;
  58939. 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;
  58940. 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;
  58941. }
  58942. bBox._update(this.mesh._worldMatrix);
  58943. }
  58944. // place and scale the particle bouding sphere in the SPS local system, then update it
  58945. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58946. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58947. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58948. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58949. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58950. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58951. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58952. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58953. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58954. 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));
  58955. bSphere._update(this.mesh._worldMatrix);
  58956. }
  58957. // increment indexes for the next particle
  58958. index = idx + 3;
  58959. colorIndex = colidx + 4;
  58960. uvIndex = uvidx + 2;
  58961. }
  58962. // if the VBO must be updated
  58963. if (update) {
  58964. if (this._computeParticleColor) {
  58965. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58966. }
  58967. if (this._computeParticleTexture) {
  58968. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58969. }
  58970. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58971. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58972. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58973. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58974. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58975. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58976. for (var i = 0; i < this._normals32.length; i++) {
  58977. this._fixedNormal32[i] = this._normals32[i];
  58978. }
  58979. }
  58980. if (!this.mesh.areNormalsFrozen) {
  58981. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58982. }
  58983. }
  58984. if (this._depthSort && this._depthSortParticles) {
  58985. this.depthSortedParticles.sort(this._depthSortFunction);
  58986. var dspl = this.depthSortedParticles.length;
  58987. var sorted = 0;
  58988. var lind = 0;
  58989. var sind = 0;
  58990. var sid = 0;
  58991. for (sorted = 0; sorted < dspl; sorted++) {
  58992. lind = this.depthSortedParticles[sorted].indicesLength;
  58993. sind = this.depthSortedParticles[sorted].ind;
  58994. for (var i = 0; i < lind; i++) {
  58995. this._indices32[sid] = this._indices[sind + i];
  58996. sid++;
  58997. }
  58998. }
  58999. this.mesh.updateIndices(this._indices32);
  59000. }
  59001. }
  59002. if (this._computeBoundingBox) {
  59003. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59004. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59005. }
  59006. this.afterUpdateParticles(start, end, update);
  59007. return this;
  59008. };
  59009. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59010. this._halfroll = this._roll * 0.5;
  59011. this._halfpitch = this._pitch * 0.5;
  59012. this._halfyaw = this._yaw * 0.5;
  59013. this._sinRoll = Math.sin(this._halfroll);
  59014. this._cosRoll = Math.cos(this._halfroll);
  59015. this._sinPitch = Math.sin(this._halfpitch);
  59016. this._cosPitch = Math.cos(this._halfpitch);
  59017. this._sinYaw = Math.sin(this._halfyaw);
  59018. this._cosYaw = Math.cos(this._halfyaw);
  59019. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59020. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59021. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59022. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59023. };
  59024. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59025. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59026. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59027. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59028. this._rotMatrix.m[3] = 0;
  59029. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59030. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59031. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59032. this._rotMatrix.m[7] = 0;
  59033. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59034. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59035. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59036. this._rotMatrix.m[11] = 0;
  59037. this._rotMatrix.m[12] = 0;
  59038. this._rotMatrix.m[13] = 0;
  59039. this._rotMatrix.m[14] = 0;
  59040. this._rotMatrix.m[15] = 1.0;
  59041. };
  59042. /**
  59043. * Disposes the SPS.
  59044. */
  59045. SolidParticleSystem.prototype.dispose = function () {
  59046. this.mesh.dispose();
  59047. this.vars = null;
  59048. // drop references to internal big arrays for the GC
  59049. this._positions = null;
  59050. this._indices = null;
  59051. this._normals = null;
  59052. this._uvs = null;
  59053. this._colors = null;
  59054. this._indices32 = null;
  59055. this._positions32 = null;
  59056. this._normals32 = null;
  59057. this._fixedNormal32 = null;
  59058. this._uvs32 = null;
  59059. this._colors32 = null;
  59060. this.pickedParticles = null;
  59061. };
  59062. /**
  59063. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59064. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59065. * @returns the SPS.
  59066. */
  59067. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59068. if (!this._isVisibilityBoxLocked) {
  59069. this.mesh.refreshBoundingInfo();
  59070. }
  59071. return this;
  59072. };
  59073. /**
  59074. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59075. * @param size the size (float) of the visibility box
  59076. * note : this doesn't lock the SPS mesh bounding box.
  59077. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59078. */
  59079. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59080. var vis = size / 2;
  59081. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59082. };
  59083. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59084. /**
  59085. * Gets whether the SPS as always visible or not
  59086. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59087. */
  59088. get: function () {
  59089. return this._alwaysVisible;
  59090. },
  59091. /**
  59092. * Sets the SPS as always visible or not
  59093. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59094. */
  59095. set: function (val) {
  59096. this._alwaysVisible = val;
  59097. this.mesh.alwaysSelectAsActiveMesh = val;
  59098. },
  59099. enumerable: true,
  59100. configurable: true
  59101. });
  59102. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59103. /**
  59104. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59105. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59106. */
  59107. get: function () {
  59108. return this._isVisibilityBoxLocked;
  59109. },
  59110. /**
  59111. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59112. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59113. */
  59114. set: function (val) {
  59115. this._isVisibilityBoxLocked = val;
  59116. var boundingInfo = this.mesh.getBoundingInfo();
  59117. boundingInfo.isLocked = val;
  59118. },
  59119. enumerable: true,
  59120. configurable: true
  59121. });
  59122. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59123. /**
  59124. * Gets if `setParticles()` computes the particle rotations or not.
  59125. * Default value : true. The SPS is faster when it's set to false.
  59126. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59127. */
  59128. get: function () {
  59129. return this._computeParticleRotation;
  59130. },
  59131. /**
  59132. * Tells to `setParticles()` to compute the particle rotations or not.
  59133. * Default value : true. The SPS is faster when it's set to false.
  59134. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59135. */
  59136. set: function (val) {
  59137. this._computeParticleRotation = val;
  59138. },
  59139. enumerable: true,
  59140. configurable: true
  59141. });
  59142. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59143. /**
  59144. * Gets if `setParticles()` computes the particle colors or not.
  59145. * Default value : true. The SPS is faster when it's set to false.
  59146. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59147. */
  59148. get: function () {
  59149. return this._computeParticleColor;
  59150. },
  59151. /**
  59152. * Tells to `setParticles()` to compute the particle colors or not.
  59153. * Default value : true. The SPS is faster when it's set to false.
  59154. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59155. */
  59156. set: function (val) {
  59157. this._computeParticleColor = val;
  59158. },
  59159. enumerable: true,
  59160. configurable: true
  59161. });
  59162. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59163. /**
  59164. * Gets if `setParticles()` computes the particle textures or not.
  59165. * Default value : true. The SPS is faster when it's set to false.
  59166. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59167. */
  59168. get: function () {
  59169. return this._computeParticleTexture;
  59170. },
  59171. set: function (val) {
  59172. this._computeParticleTexture = val;
  59173. },
  59174. enumerable: true,
  59175. configurable: true
  59176. });
  59177. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59178. /**
  59179. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59180. * Default value : false. The SPS is faster when it's set to false.
  59181. * Note : the particle custom vertex positions aren't stored values.
  59182. */
  59183. get: function () {
  59184. return this._computeParticleVertex;
  59185. },
  59186. /**
  59187. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59188. * Default value : false. The SPS is faster when it's set to false.
  59189. * Note : the particle custom vertex positions aren't stored values.
  59190. */
  59191. set: function (val) {
  59192. this._computeParticleVertex = val;
  59193. },
  59194. enumerable: true,
  59195. configurable: true
  59196. });
  59197. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59198. /**
  59199. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59200. */
  59201. get: function () {
  59202. return this._computeBoundingBox;
  59203. },
  59204. /**
  59205. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59206. */
  59207. set: function (val) {
  59208. this._computeBoundingBox = val;
  59209. },
  59210. enumerable: true,
  59211. configurable: true
  59212. });
  59213. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59214. /**
  59215. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59216. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59217. * Default : `true`
  59218. */
  59219. get: function () {
  59220. return this._depthSortParticles;
  59221. },
  59222. /**
  59223. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59224. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59225. * Default : `true`
  59226. */
  59227. set: function (val) {
  59228. this._depthSortParticles = val;
  59229. },
  59230. enumerable: true,
  59231. configurable: true
  59232. });
  59233. // =======================================================================
  59234. // Particle behavior logic
  59235. // these following methods may be overwritten by the user to fit his needs
  59236. /**
  59237. * This function does nothing. It may be overwritten to set all the particle first values.
  59238. * The SPS doesn't call this function, you may have to call it by your own.
  59239. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59240. */
  59241. SolidParticleSystem.prototype.initParticles = function () {
  59242. };
  59243. /**
  59244. * This function does nothing. It may be overwritten to recycle a particle.
  59245. * The SPS doesn't call this function, you may have to call it by your own.
  59246. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59247. * @param particle The particle to recycle
  59248. * @returns the recycled particle
  59249. */
  59250. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59251. return particle;
  59252. };
  59253. /**
  59254. * Updates a particle : this function should be overwritten by the user.
  59255. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59256. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59257. * @example : just set a particle position or velocity and recycle conditions
  59258. * @param particle The particle to update
  59259. * @returns the updated particle
  59260. */
  59261. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59262. return particle;
  59263. };
  59264. /**
  59265. * Updates a vertex of a particle : it can be overwritten by the user.
  59266. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59267. * @param particle the current particle
  59268. * @param vertex the current index of the current particle
  59269. * @param pt the index of the current vertex in the particle shape
  59270. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59271. * @example : just set a vertex particle position
  59272. * @returns the updated vertex
  59273. */
  59274. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59275. return vertex;
  59276. };
  59277. /**
  59278. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59279. * This does nothing and may be overwritten by the user.
  59280. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59281. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59282. * @param update the boolean update value actually passed to setParticles()
  59283. */
  59284. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59285. };
  59286. /**
  59287. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59288. * This will be passed three parameters.
  59289. * This does nothing and may be overwritten by the user.
  59290. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59291. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59292. * @param update the boolean update value actually passed to setParticles()
  59293. */
  59294. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59295. };
  59296. return SolidParticleSystem;
  59297. }());
  59298. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59299. })(BABYLON || (BABYLON = {}));
  59300. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59301. var BABYLON;
  59302. (function (BABYLON) {
  59303. var ShaderMaterial = /** @class */ (function (_super) {
  59304. __extends(ShaderMaterial, _super);
  59305. function ShaderMaterial(name, scene, shaderPath, options) {
  59306. var _this = _super.call(this, name, scene) || this;
  59307. _this._textures = {};
  59308. _this._textureArrays = {};
  59309. _this._floats = {};
  59310. _this._ints = {};
  59311. _this._floatsArrays = {};
  59312. _this._colors3 = {};
  59313. _this._colors3Arrays = {};
  59314. _this._colors4 = {};
  59315. _this._vectors2 = {};
  59316. _this._vectors3 = {};
  59317. _this._vectors4 = {};
  59318. _this._matrices = {};
  59319. _this._matrices3x3 = {};
  59320. _this._matrices2x2 = {};
  59321. _this._vectors2Arrays = {};
  59322. _this._vectors3Arrays = {};
  59323. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59324. _this._shaderPath = shaderPath;
  59325. options.needAlphaBlending = options.needAlphaBlending || false;
  59326. options.needAlphaTesting = options.needAlphaTesting || false;
  59327. options.attributes = options.attributes || ["position", "normal", "uv"];
  59328. options.uniforms = options.uniforms || ["worldViewProjection"];
  59329. options.uniformBuffers = options.uniformBuffers || [];
  59330. options.samplers = options.samplers || [];
  59331. options.defines = options.defines || [];
  59332. _this._options = options;
  59333. return _this;
  59334. }
  59335. ShaderMaterial.prototype.getClassName = function () {
  59336. return "ShaderMaterial";
  59337. };
  59338. ShaderMaterial.prototype.needAlphaBlending = function () {
  59339. return this._options.needAlphaBlending;
  59340. };
  59341. ShaderMaterial.prototype.needAlphaTesting = function () {
  59342. return this._options.needAlphaTesting;
  59343. };
  59344. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59345. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59346. this._options.uniforms.push(uniformName);
  59347. }
  59348. };
  59349. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59350. if (this._options.samplers.indexOf(name) === -1) {
  59351. this._options.samplers.push(name);
  59352. }
  59353. this._textures[name] = texture;
  59354. return this;
  59355. };
  59356. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59357. if (this._options.samplers.indexOf(name) === -1) {
  59358. this._options.samplers.push(name);
  59359. }
  59360. this._checkUniform(name);
  59361. this._textureArrays[name] = textures;
  59362. return this;
  59363. };
  59364. ShaderMaterial.prototype.setFloat = function (name, value) {
  59365. this._checkUniform(name);
  59366. this._floats[name] = value;
  59367. return this;
  59368. };
  59369. ShaderMaterial.prototype.setInt = function (name, value) {
  59370. this._checkUniform(name);
  59371. this._ints[name] = value;
  59372. return this;
  59373. };
  59374. ShaderMaterial.prototype.setFloats = function (name, value) {
  59375. this._checkUniform(name);
  59376. this._floatsArrays[name] = value;
  59377. return this;
  59378. };
  59379. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59380. this._checkUniform(name);
  59381. this._colors3[name] = value;
  59382. return this;
  59383. };
  59384. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59385. this._checkUniform(name);
  59386. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59387. color.toArray(arr, arr.length);
  59388. return arr;
  59389. }, []);
  59390. return this;
  59391. };
  59392. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59393. this._checkUniform(name);
  59394. this._colors4[name] = value;
  59395. return this;
  59396. };
  59397. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59398. this._checkUniform(name);
  59399. this._vectors2[name] = value;
  59400. return this;
  59401. };
  59402. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59403. this._checkUniform(name);
  59404. this._vectors3[name] = value;
  59405. return this;
  59406. };
  59407. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59408. this._checkUniform(name);
  59409. this._vectors4[name] = value;
  59410. return this;
  59411. };
  59412. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59413. this._checkUniform(name);
  59414. this._matrices[name] = value;
  59415. return this;
  59416. };
  59417. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59418. this._checkUniform(name);
  59419. this._matrices3x3[name] = value;
  59420. return this;
  59421. };
  59422. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59423. this._checkUniform(name);
  59424. this._matrices2x2[name] = value;
  59425. return this;
  59426. };
  59427. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59428. this._checkUniform(name);
  59429. this._vectors2Arrays[name] = value;
  59430. return this;
  59431. };
  59432. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59433. this._checkUniform(name);
  59434. this._vectors3Arrays[name] = value;
  59435. return this;
  59436. };
  59437. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59438. if (!mesh) {
  59439. return true;
  59440. }
  59441. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59442. return false;
  59443. }
  59444. return false;
  59445. };
  59446. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59447. var scene = this.getScene();
  59448. var engine = scene.getEngine();
  59449. if (!this.checkReadyOnEveryCall) {
  59450. if (this._renderId === scene.getRenderId()) {
  59451. if (this._checkCache(scene, mesh, useInstances)) {
  59452. return true;
  59453. }
  59454. }
  59455. }
  59456. // Instances
  59457. var defines = [];
  59458. var attribs = [];
  59459. var fallbacks = new BABYLON.EffectFallbacks();
  59460. if (useInstances) {
  59461. defines.push("#define INSTANCES");
  59462. }
  59463. for (var index = 0; index < this._options.defines.length; index++) {
  59464. defines.push(this._options.defines[index]);
  59465. }
  59466. for (var index = 0; index < this._options.attributes.length; index++) {
  59467. attribs.push(this._options.attributes[index]);
  59468. }
  59469. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59470. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59471. defines.push("#define VERTEXCOLOR");
  59472. }
  59473. // Bones
  59474. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59475. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59476. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59477. if (mesh.numBoneInfluencers > 4) {
  59478. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59479. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59480. }
  59481. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59482. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59483. fallbacks.addCPUSkinningFallback(0, mesh);
  59484. if (this._options.uniforms.indexOf("mBones") === -1) {
  59485. this._options.uniforms.push("mBones");
  59486. }
  59487. }
  59488. else {
  59489. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59490. }
  59491. // Textures
  59492. for (var name in this._textures) {
  59493. if (!this._textures[name].isReady()) {
  59494. return false;
  59495. }
  59496. }
  59497. // Alpha test
  59498. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59499. defines.push("#define ALPHATEST");
  59500. }
  59501. var previousEffect = this._effect;
  59502. var join = defines.join("\n");
  59503. this._effect = engine.createEffect(this._shaderPath, {
  59504. attributes: attribs,
  59505. uniformsNames: this._options.uniforms,
  59506. uniformBuffersNames: this._options.uniformBuffers,
  59507. samplers: this._options.samplers,
  59508. defines: join,
  59509. fallbacks: fallbacks,
  59510. onCompiled: this.onCompiled,
  59511. onError: this.onError
  59512. }, engine);
  59513. if (!this._effect.isReady()) {
  59514. return false;
  59515. }
  59516. if (previousEffect !== this._effect) {
  59517. scene.resetCachedMaterial();
  59518. }
  59519. this._renderId = scene.getRenderId();
  59520. return true;
  59521. };
  59522. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59523. var scene = this.getScene();
  59524. if (!this._effect) {
  59525. return;
  59526. }
  59527. if (this._options.uniforms.indexOf("world") !== -1) {
  59528. this._effect.setMatrix("world", world);
  59529. }
  59530. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59531. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59532. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59533. }
  59534. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59535. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59536. }
  59537. };
  59538. ShaderMaterial.prototype.bind = function (world, mesh) {
  59539. // Std values
  59540. this.bindOnlyWorldMatrix(world);
  59541. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59542. if (this._options.uniforms.indexOf("view") !== -1) {
  59543. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59544. }
  59545. if (this._options.uniforms.indexOf("projection") !== -1) {
  59546. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59547. }
  59548. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59549. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59550. }
  59551. // Bones
  59552. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59553. var name;
  59554. // Texture
  59555. for (name in this._textures) {
  59556. this._effect.setTexture(name, this._textures[name]);
  59557. }
  59558. // Texture arrays
  59559. for (name in this._textureArrays) {
  59560. this._effect.setTextureArray(name, this._textureArrays[name]);
  59561. }
  59562. // Int
  59563. for (name in this._ints) {
  59564. this._effect.setInt(name, this._ints[name]);
  59565. }
  59566. // Float
  59567. for (name in this._floats) {
  59568. this._effect.setFloat(name, this._floats[name]);
  59569. }
  59570. // Floats
  59571. for (name in this._floatsArrays) {
  59572. this._effect.setArray(name, this._floatsArrays[name]);
  59573. }
  59574. // Color3
  59575. for (name in this._colors3) {
  59576. this._effect.setColor3(name, this._colors3[name]);
  59577. }
  59578. for (name in this._colors3Arrays) {
  59579. this._effect.setArray3(name, this._colors3Arrays[name]);
  59580. }
  59581. // Color4
  59582. for (name in this._colors4) {
  59583. var color = this._colors4[name];
  59584. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59585. }
  59586. // Vector2
  59587. for (name in this._vectors2) {
  59588. this._effect.setVector2(name, this._vectors2[name]);
  59589. }
  59590. // Vector3
  59591. for (name in this._vectors3) {
  59592. this._effect.setVector3(name, this._vectors3[name]);
  59593. }
  59594. // Vector4
  59595. for (name in this._vectors4) {
  59596. this._effect.setVector4(name, this._vectors4[name]);
  59597. }
  59598. // Matrix
  59599. for (name in this._matrices) {
  59600. this._effect.setMatrix(name, this._matrices[name]);
  59601. }
  59602. // Matrix 3x3
  59603. for (name in this._matrices3x3) {
  59604. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59605. }
  59606. // Matrix 2x2
  59607. for (name in this._matrices2x2) {
  59608. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59609. }
  59610. // Vector2Array
  59611. for (name in this._vectors2Arrays) {
  59612. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59613. }
  59614. // Vector3Array
  59615. for (name in this._vectors3Arrays) {
  59616. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59617. }
  59618. }
  59619. this._afterBind(mesh);
  59620. };
  59621. ShaderMaterial.prototype.getActiveTextures = function () {
  59622. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59623. for (var name in this._textures) {
  59624. activeTextures.push(this._textures[name]);
  59625. }
  59626. for (var name in this._textureArrays) {
  59627. var array = this._textureArrays[name];
  59628. for (var index = 0; index < array.length; index++) {
  59629. activeTextures.push(array[index]);
  59630. }
  59631. }
  59632. return activeTextures;
  59633. };
  59634. ShaderMaterial.prototype.hasTexture = function (texture) {
  59635. if (_super.prototype.hasTexture.call(this, texture)) {
  59636. return true;
  59637. }
  59638. for (var name in this._textures) {
  59639. if (this._textures[name] === texture) {
  59640. return true;
  59641. }
  59642. }
  59643. for (var name in this._textureArrays) {
  59644. var array = this._textureArrays[name];
  59645. for (var index = 0; index < array.length; index++) {
  59646. if (array[index] === texture) {
  59647. return true;
  59648. }
  59649. }
  59650. }
  59651. return false;
  59652. };
  59653. ShaderMaterial.prototype.clone = function (name) {
  59654. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59655. return newShaderMaterial;
  59656. };
  59657. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59658. if (forceDisposeTextures) {
  59659. var name;
  59660. for (name in this._textures) {
  59661. this._textures[name].dispose();
  59662. }
  59663. for (name in this._textureArrays) {
  59664. var array = this._textureArrays[name];
  59665. for (var index = 0; index < array.length; index++) {
  59666. array[index].dispose();
  59667. }
  59668. }
  59669. }
  59670. this._textures = {};
  59671. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59672. };
  59673. ShaderMaterial.prototype.serialize = function () {
  59674. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59675. serializationObject.customType = "BABYLON.ShaderMaterial";
  59676. serializationObject.options = this._options;
  59677. serializationObject.shaderPath = this._shaderPath;
  59678. var name;
  59679. // Texture
  59680. serializationObject.textures = {};
  59681. for (name in this._textures) {
  59682. serializationObject.textures[name] = this._textures[name].serialize();
  59683. }
  59684. // Texture arrays
  59685. serializationObject.textureArrays = {};
  59686. for (name in this._textureArrays) {
  59687. serializationObject.textureArrays[name] = [];
  59688. var array = this._textureArrays[name];
  59689. for (var index = 0; index < array.length; index++) {
  59690. serializationObject.textureArrays[name].push(array[index].serialize());
  59691. }
  59692. }
  59693. // Float
  59694. serializationObject.floats = {};
  59695. for (name in this._floats) {
  59696. serializationObject.floats[name] = this._floats[name];
  59697. }
  59698. // Float s
  59699. serializationObject.FloatArrays = {};
  59700. for (name in this._floatsArrays) {
  59701. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59702. }
  59703. // Color3
  59704. serializationObject.colors3 = {};
  59705. for (name in this._colors3) {
  59706. serializationObject.colors3[name] = this._colors3[name].asArray();
  59707. }
  59708. // Color3 array
  59709. serializationObject.colors3Arrays = {};
  59710. for (name in this._colors3Arrays) {
  59711. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59712. }
  59713. // Color4
  59714. serializationObject.colors4 = {};
  59715. for (name in this._colors4) {
  59716. serializationObject.colors4[name] = this._colors4[name].asArray();
  59717. }
  59718. // Vector2
  59719. serializationObject.vectors2 = {};
  59720. for (name in this._vectors2) {
  59721. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59722. }
  59723. // Vector3
  59724. serializationObject.vectors3 = {};
  59725. for (name in this._vectors3) {
  59726. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59727. }
  59728. // Vector4
  59729. serializationObject.vectors4 = {};
  59730. for (name in this._vectors4) {
  59731. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59732. }
  59733. // Matrix
  59734. serializationObject.matrices = {};
  59735. for (name in this._matrices) {
  59736. serializationObject.matrices[name] = this._matrices[name].asArray();
  59737. }
  59738. // Matrix 3x3
  59739. serializationObject.matrices3x3 = {};
  59740. for (name in this._matrices3x3) {
  59741. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59742. }
  59743. // Matrix 2x2
  59744. serializationObject.matrices2x2 = {};
  59745. for (name in this._matrices2x2) {
  59746. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59747. }
  59748. // Vector2Array
  59749. serializationObject.vectors2Arrays = {};
  59750. for (name in this._vectors2Arrays) {
  59751. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59752. }
  59753. // Vector3Array
  59754. serializationObject.vectors3Arrays = {};
  59755. for (name in this._vectors3Arrays) {
  59756. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59757. }
  59758. return serializationObject;
  59759. };
  59760. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59761. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59762. var name;
  59763. // Texture
  59764. for (name in source.textures) {
  59765. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59766. }
  59767. // Texture arrays
  59768. for (name in source.textureArrays) {
  59769. var array = source.textureArrays[name];
  59770. var textureArray = new Array();
  59771. for (var index = 0; index < array.length; index++) {
  59772. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59773. }
  59774. material.setTextureArray(name, textureArray);
  59775. }
  59776. // Float
  59777. for (name in source.floats) {
  59778. material.setFloat(name, source.floats[name]);
  59779. }
  59780. // Float s
  59781. for (name in source.floatsArrays) {
  59782. material.setFloats(name, source.floatsArrays[name]);
  59783. }
  59784. // Color3
  59785. for (name in source.colors3) {
  59786. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59787. }
  59788. // Color3 arrays
  59789. for (name in source.colors3Arrays) {
  59790. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59791. if (i % 3 === 0) {
  59792. arr.push([num]);
  59793. }
  59794. else {
  59795. arr[arr.length - 1].push(num);
  59796. }
  59797. return arr;
  59798. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59799. material.setColor3Array(name, colors);
  59800. }
  59801. // Color4
  59802. for (name in source.colors4) {
  59803. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59804. }
  59805. // Vector2
  59806. for (name in source.vectors2) {
  59807. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59808. }
  59809. // Vector3
  59810. for (name in source.vectors3) {
  59811. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59812. }
  59813. // Vector4
  59814. for (name in source.vectors4) {
  59815. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59816. }
  59817. // Matrix
  59818. for (name in source.matrices) {
  59819. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59820. }
  59821. // Matrix 3x3
  59822. for (name in source.matrices3x3) {
  59823. material.setMatrix3x3(name, source.matrices3x3[name]);
  59824. }
  59825. // Matrix 2x2
  59826. for (name in source.matrices2x2) {
  59827. material.setMatrix2x2(name, source.matrices2x2[name]);
  59828. }
  59829. // Vector2Array
  59830. for (name in source.vectors2Arrays) {
  59831. material.setArray2(name, source.vectors2Arrays[name]);
  59832. }
  59833. // Vector3Array
  59834. for (name in source.vectors3Arrays) {
  59835. material.setArray3(name, source.vectors3Arrays[name]);
  59836. }
  59837. return material;
  59838. };
  59839. return ShaderMaterial;
  59840. }(BABYLON.Material));
  59841. BABYLON.ShaderMaterial = ShaderMaterial;
  59842. })(BABYLON || (BABYLON = {}));
  59843. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59844. var BABYLON;
  59845. (function (BABYLON) {
  59846. var GroundMesh = /** @class */ (function (_super) {
  59847. __extends(GroundMesh, _super);
  59848. function GroundMesh(name, scene) {
  59849. var _this = _super.call(this, name, scene) || this;
  59850. _this.generateOctree = false;
  59851. return _this;
  59852. }
  59853. GroundMesh.prototype.getClassName = function () {
  59854. return "GroundMesh";
  59855. };
  59856. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59857. get: function () {
  59858. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59859. },
  59860. enumerable: true,
  59861. configurable: true
  59862. });
  59863. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59864. get: function () {
  59865. return this._subdivisionsX;
  59866. },
  59867. enumerable: true,
  59868. configurable: true
  59869. });
  59870. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59871. get: function () {
  59872. return this._subdivisionsY;
  59873. },
  59874. enumerable: true,
  59875. configurable: true
  59876. });
  59877. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59878. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59879. this._subdivisionsX = chunksCount;
  59880. this._subdivisionsY = chunksCount;
  59881. this.subdivide(chunksCount);
  59882. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59883. };
  59884. /**
  59885. * Returns a height (y) value in the Worl system :
  59886. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59887. * Returns the ground y position if (x, z) are outside the ground surface.
  59888. */
  59889. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59890. var world = this.getWorldMatrix();
  59891. var invMat = BABYLON.Tmp.Matrix[5];
  59892. world.invertToRef(invMat);
  59893. var tmpVect = BABYLON.Tmp.Vector3[8];
  59894. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59895. x = tmpVect.x;
  59896. z = tmpVect.z;
  59897. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59898. return this.position.y;
  59899. }
  59900. if (!this._heightQuads || this._heightQuads.length == 0) {
  59901. this._initHeightQuads();
  59902. this._computeHeightQuads();
  59903. }
  59904. var facet = this._getFacetAt(x, z);
  59905. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59906. // return y in the World system
  59907. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59908. return tmpVect.y;
  59909. };
  59910. /**
  59911. * Returns a normalized vector (Vector3) orthogonal to the ground
  59912. * at the ground coordinates (x, z) expressed in the World system.
  59913. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59914. */
  59915. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59916. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59917. this.getNormalAtCoordinatesToRef(x, z, normal);
  59918. return normal;
  59919. };
  59920. /**
  59921. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59922. * at the ground coordinates (x, z) expressed in the World system.
  59923. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59924. * Returns the GroundMesh.
  59925. */
  59926. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59927. var world = this.getWorldMatrix();
  59928. var tmpMat = BABYLON.Tmp.Matrix[5];
  59929. world.invertToRef(tmpMat);
  59930. var tmpVect = BABYLON.Tmp.Vector3[8];
  59931. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59932. x = tmpVect.x;
  59933. z = tmpVect.z;
  59934. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59935. return this;
  59936. }
  59937. if (!this._heightQuads || this._heightQuads.length == 0) {
  59938. this._initHeightQuads();
  59939. this._computeHeightQuads();
  59940. }
  59941. var facet = this._getFacetAt(x, z);
  59942. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59943. return this;
  59944. };
  59945. /**
  59946. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59947. * if the ground has been updated.
  59948. * This can be used in the render loop.
  59949. * Returns the GroundMesh.
  59950. */
  59951. GroundMesh.prototype.updateCoordinateHeights = function () {
  59952. if (!this._heightQuads || this._heightQuads.length == 0) {
  59953. this._initHeightQuads();
  59954. }
  59955. this._computeHeightQuads();
  59956. return this;
  59957. };
  59958. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59959. GroundMesh.prototype._getFacetAt = function (x, z) {
  59960. // retrieve col and row from x, z coordinates in the ground local system
  59961. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59962. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59963. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59964. var facet;
  59965. if (z < quad.slope.x * x + quad.slope.y) {
  59966. facet = quad.facet1;
  59967. }
  59968. else {
  59969. facet = quad.facet2;
  59970. }
  59971. return facet;
  59972. };
  59973. // Creates and populates the heightMap array with "facet" elements :
  59974. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59975. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59976. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59977. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59978. // Returns the GroundMesh.
  59979. GroundMesh.prototype._initHeightQuads = function () {
  59980. var subdivisionsX = this._subdivisionsX;
  59981. var subdivisionsY = this._subdivisionsY;
  59982. this._heightQuads = new Array();
  59983. for (var row = 0; row < subdivisionsY; row++) {
  59984. for (var col = 0; col < subdivisionsX; col++) {
  59985. 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) };
  59986. this._heightQuads[row * subdivisionsX + col] = quad;
  59987. }
  59988. }
  59989. return this;
  59990. };
  59991. // Compute each quad element values and update the the heightMap array :
  59992. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59993. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59994. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59995. // Returns the GroundMesh.
  59996. GroundMesh.prototype._computeHeightQuads = function () {
  59997. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59998. if (!positions) {
  59999. return this;
  60000. }
  60001. var v1 = BABYLON.Tmp.Vector3[3];
  60002. var v2 = BABYLON.Tmp.Vector3[2];
  60003. var v3 = BABYLON.Tmp.Vector3[1];
  60004. var v4 = BABYLON.Tmp.Vector3[0];
  60005. var v1v2 = BABYLON.Tmp.Vector3[4];
  60006. var v1v3 = BABYLON.Tmp.Vector3[5];
  60007. var v1v4 = BABYLON.Tmp.Vector3[6];
  60008. var norm1 = BABYLON.Tmp.Vector3[7];
  60009. var norm2 = BABYLON.Tmp.Vector3[8];
  60010. var i = 0;
  60011. var j = 0;
  60012. var k = 0;
  60013. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60014. var h = 0;
  60015. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60016. var d2 = 0;
  60017. var subdivisionsX = this._subdivisionsX;
  60018. var subdivisionsY = this._subdivisionsY;
  60019. for (var row = 0; row < subdivisionsY; row++) {
  60020. for (var col = 0; col < subdivisionsX; col++) {
  60021. i = col * 3;
  60022. j = row * (subdivisionsX + 1) * 3;
  60023. k = (row + 1) * (subdivisionsX + 1) * 3;
  60024. v1.x = positions[j + i];
  60025. v1.y = positions[j + i + 1];
  60026. v1.z = positions[j + i + 2];
  60027. v2.x = positions[j + i + 3];
  60028. v2.y = positions[j + i + 4];
  60029. v2.z = positions[j + i + 5];
  60030. v3.x = positions[k + i];
  60031. v3.y = positions[k + i + 1];
  60032. v3.z = positions[k + i + 2];
  60033. v4.x = positions[k + i + 3];
  60034. v4.y = positions[k + i + 4];
  60035. v4.z = positions[k + i + 5];
  60036. // 2D slope V1V4
  60037. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60038. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60039. // facet equations :
  60040. // we compute each facet normal vector
  60041. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60042. // we compute the value d by applying the equation to v1 which belongs to the plane
  60043. // then we store the facet equation in a Vector4
  60044. v2.subtractToRef(v1, v1v2);
  60045. v3.subtractToRef(v1, v1v3);
  60046. v4.subtractToRef(v1, v1v4);
  60047. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60048. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60049. norm1.normalize();
  60050. norm2.normalize();
  60051. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60052. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60053. var quad = this._heightQuads[row * subdivisionsX + col];
  60054. quad.slope.copyFromFloats(cd, h);
  60055. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60056. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60057. }
  60058. }
  60059. return this;
  60060. };
  60061. GroundMesh.prototype.serialize = function (serializationObject) {
  60062. _super.prototype.serialize.call(this, serializationObject);
  60063. serializationObject.subdivisionsX = this._subdivisionsX;
  60064. serializationObject.subdivisionsY = this._subdivisionsY;
  60065. serializationObject.minX = this._minX;
  60066. serializationObject.maxX = this._maxX;
  60067. serializationObject.minZ = this._minZ;
  60068. serializationObject.maxZ = this._maxZ;
  60069. serializationObject.width = this._width;
  60070. serializationObject.height = this._height;
  60071. };
  60072. GroundMesh.Parse = function (parsedMesh, scene) {
  60073. var result = new GroundMesh(parsedMesh.name, scene);
  60074. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60075. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60076. result._minX = parsedMesh.minX;
  60077. result._maxX = parsedMesh.maxX;
  60078. result._minZ = parsedMesh.minZ;
  60079. result._maxZ = parsedMesh.maxZ;
  60080. result._width = parsedMesh.width;
  60081. result._height = parsedMesh.height;
  60082. return result;
  60083. };
  60084. return GroundMesh;
  60085. }(BABYLON.Mesh));
  60086. BABYLON.GroundMesh = GroundMesh;
  60087. })(BABYLON || (BABYLON = {}));
  60088. //# sourceMappingURL=babylon.groundMesh.js.map
  60089. var BABYLON;
  60090. (function (BABYLON) {
  60091. /**
  60092. * Creates an instance based on a source mesh.
  60093. */
  60094. var InstancedMesh = /** @class */ (function (_super) {
  60095. __extends(InstancedMesh, _super);
  60096. function InstancedMesh(name, source) {
  60097. var _this = _super.call(this, name, source.getScene()) || this;
  60098. source.instances.push(_this);
  60099. _this._sourceMesh = source;
  60100. _this.position.copyFrom(source.position);
  60101. _this.rotation.copyFrom(source.rotation);
  60102. _this.scaling.copyFrom(source.scaling);
  60103. if (source.rotationQuaternion) {
  60104. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60105. }
  60106. _this.infiniteDistance = source.infiniteDistance;
  60107. _this.setPivotMatrix(source.getPivotMatrix());
  60108. _this.refreshBoundingInfo();
  60109. _this._syncSubMeshes();
  60110. return _this;
  60111. }
  60112. /**
  60113. * Returns the string "InstancedMesh".
  60114. */
  60115. InstancedMesh.prototype.getClassName = function () {
  60116. return "InstancedMesh";
  60117. };
  60118. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60119. // Methods
  60120. get: function () {
  60121. return this._sourceMesh.receiveShadows;
  60122. },
  60123. enumerable: true,
  60124. configurable: true
  60125. });
  60126. Object.defineProperty(InstancedMesh.prototype, "material", {
  60127. get: function () {
  60128. return this._sourceMesh.material;
  60129. },
  60130. enumerable: true,
  60131. configurable: true
  60132. });
  60133. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60134. get: function () {
  60135. return this._sourceMesh.visibility;
  60136. },
  60137. enumerable: true,
  60138. configurable: true
  60139. });
  60140. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60141. get: function () {
  60142. return this._sourceMesh.skeleton;
  60143. },
  60144. enumerable: true,
  60145. configurable: true
  60146. });
  60147. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60148. get: function () {
  60149. return this._sourceMesh.renderingGroupId;
  60150. },
  60151. set: function (value) {
  60152. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60153. return;
  60154. }
  60155. //no-op with warning
  60156. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60157. },
  60158. enumerable: true,
  60159. configurable: true
  60160. });
  60161. /**
  60162. * Returns the total number of vertices (integer).
  60163. */
  60164. InstancedMesh.prototype.getTotalVertices = function () {
  60165. return this._sourceMesh.getTotalVertices();
  60166. };
  60167. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60168. get: function () {
  60169. return this._sourceMesh;
  60170. },
  60171. enumerable: true,
  60172. configurable: true
  60173. });
  60174. /**
  60175. * Is this node ready to be used/rendered
  60176. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60177. * @return {boolean} is it ready
  60178. */
  60179. InstancedMesh.prototype.isReady = function (completeCheck) {
  60180. if (completeCheck === void 0) { completeCheck = false; }
  60181. return this._sourceMesh.isReady(completeCheck, true);
  60182. };
  60183. /**
  60184. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60185. */
  60186. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60187. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60188. };
  60189. /**
  60190. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60191. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60192. * The `data` are either a numeric array either a Float32Array.
  60193. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60194. * 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).
  60195. * Note that a new underlying VertexBuffer object is created each call.
  60196. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60197. *
  60198. * Possible `kind` values :
  60199. * - BABYLON.VertexBuffer.PositionKind
  60200. * - BABYLON.VertexBuffer.UVKind
  60201. * - BABYLON.VertexBuffer.UV2Kind
  60202. * - BABYLON.VertexBuffer.UV3Kind
  60203. * - BABYLON.VertexBuffer.UV4Kind
  60204. * - BABYLON.VertexBuffer.UV5Kind
  60205. * - BABYLON.VertexBuffer.UV6Kind
  60206. * - BABYLON.VertexBuffer.ColorKind
  60207. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60208. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60209. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60210. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60211. *
  60212. * Returns the Mesh.
  60213. */
  60214. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60215. if (this.sourceMesh) {
  60216. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60217. }
  60218. return this.sourceMesh;
  60219. };
  60220. /**
  60221. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60222. * If the mesh has no geometry, it is simply returned as it is.
  60223. * The `data` are either a numeric array either a Float32Array.
  60224. * No new underlying VertexBuffer object is created.
  60225. * 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.
  60226. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60227. *
  60228. * Possible `kind` values :
  60229. * - BABYLON.VertexBuffer.PositionKind
  60230. * - BABYLON.VertexBuffer.UVKind
  60231. * - BABYLON.VertexBuffer.UV2Kind
  60232. * - BABYLON.VertexBuffer.UV3Kind
  60233. * - BABYLON.VertexBuffer.UV4Kind
  60234. * - BABYLON.VertexBuffer.UV5Kind
  60235. * - BABYLON.VertexBuffer.UV6Kind
  60236. * - BABYLON.VertexBuffer.ColorKind
  60237. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60238. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60239. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60240. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60241. *
  60242. * Returns the Mesh.
  60243. */
  60244. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60245. if (this.sourceMesh) {
  60246. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60247. }
  60248. return this.sourceMesh;
  60249. };
  60250. /**
  60251. * Sets the mesh indices.
  60252. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60253. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60254. * This method creates a new index buffer each call.
  60255. * Returns the Mesh.
  60256. */
  60257. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60258. if (totalVertices === void 0) { totalVertices = null; }
  60259. if (this.sourceMesh) {
  60260. this.sourceMesh.setIndices(indices, totalVertices);
  60261. }
  60262. return this.sourceMesh;
  60263. };
  60264. /**
  60265. * Boolean : True if the mesh owns the requested kind of data.
  60266. */
  60267. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60268. return this._sourceMesh.isVerticesDataPresent(kind);
  60269. };
  60270. /**
  60271. * Returns an array of indices (IndicesArray).
  60272. */
  60273. InstancedMesh.prototype.getIndices = function () {
  60274. return this._sourceMesh.getIndices();
  60275. };
  60276. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60277. get: function () {
  60278. return this._sourceMesh._positions;
  60279. },
  60280. enumerable: true,
  60281. configurable: true
  60282. });
  60283. /**
  60284. * Sets a new updated BoundingInfo to the mesh.
  60285. * Returns the mesh.
  60286. */
  60287. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60288. var meshBB = this._sourceMesh.getBoundingInfo();
  60289. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60290. this._updateBoundingInfo();
  60291. return this;
  60292. };
  60293. InstancedMesh.prototype._preActivate = function () {
  60294. if (this._currentLOD) {
  60295. this._currentLOD._preActivate();
  60296. }
  60297. return this;
  60298. };
  60299. InstancedMesh.prototype._activate = function (renderId) {
  60300. if (this._currentLOD) {
  60301. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60302. }
  60303. return this;
  60304. };
  60305. /**
  60306. * Returns the current associated LOD AbstractMesh.
  60307. */
  60308. InstancedMesh.prototype.getLOD = function (camera) {
  60309. if (!camera) {
  60310. return this;
  60311. }
  60312. var boundingInfo = this.getBoundingInfo();
  60313. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60314. if (this._currentLOD === this.sourceMesh) {
  60315. return this;
  60316. }
  60317. return this._currentLOD;
  60318. };
  60319. InstancedMesh.prototype._syncSubMeshes = function () {
  60320. this.releaseSubMeshes();
  60321. if (this._sourceMesh.subMeshes) {
  60322. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60323. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60324. }
  60325. }
  60326. return this;
  60327. };
  60328. InstancedMesh.prototype._generatePointsArray = function () {
  60329. return this._sourceMesh._generatePointsArray();
  60330. };
  60331. /**
  60332. * Creates a new InstancedMesh from the current mesh.
  60333. * - name (string) : the cloned mesh name
  60334. * - newParent (optional Node) : the optional Node to parent the clone to.
  60335. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60336. *
  60337. * Returns the clone.
  60338. */
  60339. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60340. var result = this._sourceMesh.createInstance(name);
  60341. // Deep copy
  60342. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60343. // Bounding info
  60344. this.refreshBoundingInfo();
  60345. // Parent
  60346. if (newParent) {
  60347. result.parent = newParent;
  60348. }
  60349. if (!doNotCloneChildren) {
  60350. // Children
  60351. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60352. var mesh = this.getScene().meshes[index];
  60353. if (mesh.parent === this) {
  60354. mesh.clone(mesh.name, result);
  60355. }
  60356. }
  60357. }
  60358. result.computeWorldMatrix(true);
  60359. return result;
  60360. };
  60361. /**
  60362. * Disposes the InstancedMesh.
  60363. * Returns nothing.
  60364. */
  60365. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60366. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60367. // Remove from mesh
  60368. var index = this._sourceMesh.instances.indexOf(this);
  60369. this._sourceMesh.instances.splice(index, 1);
  60370. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60371. };
  60372. return InstancedMesh;
  60373. }(BABYLON.AbstractMesh));
  60374. BABYLON.InstancedMesh = InstancedMesh;
  60375. })(BABYLON || (BABYLON = {}));
  60376. //# sourceMappingURL=babylon.instancedMesh.js.map
  60377. var BABYLON;
  60378. (function (BABYLON) {
  60379. var LinesMesh = /** @class */ (function (_super) {
  60380. __extends(LinesMesh, _super);
  60381. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60382. if (scene === void 0) { scene = null; }
  60383. if (parent === void 0) { parent = null; }
  60384. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60385. _this.useVertexColor = useVertexColor;
  60386. _this.useVertexAlpha = useVertexAlpha;
  60387. _this.color = new BABYLON.Color3(1, 1, 1);
  60388. _this.alpha = 1;
  60389. if (source) {
  60390. _this.color = source.color.clone();
  60391. _this.alpha = source.alpha;
  60392. _this.useVertexColor = source.useVertexColor;
  60393. _this.useVertexAlpha = source.useVertexAlpha;
  60394. }
  60395. _this._intersectionThreshold = 0.1;
  60396. var defines = [];
  60397. var options = {
  60398. attributes: [BABYLON.VertexBuffer.PositionKind],
  60399. uniforms: ["world", "viewProjection"],
  60400. needAlphaBlending: true,
  60401. defines: defines
  60402. };
  60403. if (useVertexAlpha === false) {
  60404. options.needAlphaBlending = false;
  60405. }
  60406. if (!useVertexColor) {
  60407. options.uniforms.push("color");
  60408. }
  60409. else {
  60410. options.defines.push("#define VERTEXCOLOR");
  60411. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60412. }
  60413. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60414. return _this;
  60415. }
  60416. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60417. /**
  60418. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60419. * This margin is expressed in world space coordinates, so its value may vary.
  60420. * Default value is 0.1
  60421. * @returns the intersection Threshold value.
  60422. */
  60423. get: function () {
  60424. return this._intersectionThreshold;
  60425. },
  60426. /**
  60427. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60428. * This margin is expressed in world space coordinates, so its value may vary.
  60429. * @param value the new threshold to apply
  60430. */
  60431. set: function (value) {
  60432. if (this._intersectionThreshold === value) {
  60433. return;
  60434. }
  60435. this._intersectionThreshold = value;
  60436. if (this.geometry) {
  60437. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60438. }
  60439. },
  60440. enumerable: true,
  60441. configurable: true
  60442. });
  60443. /**
  60444. * Returns the string "LineMesh"
  60445. */
  60446. LinesMesh.prototype.getClassName = function () {
  60447. return "LinesMesh";
  60448. };
  60449. Object.defineProperty(LinesMesh.prototype, "material", {
  60450. get: function () {
  60451. return this._colorShader;
  60452. },
  60453. set: function (value) {
  60454. // Do nothing
  60455. },
  60456. enumerable: true,
  60457. configurable: true
  60458. });
  60459. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60460. get: function () {
  60461. return false;
  60462. },
  60463. enumerable: true,
  60464. configurable: true
  60465. });
  60466. LinesMesh.prototype.createInstance = function (name) {
  60467. throw new Error("LinesMeshes do not support createInstance.");
  60468. };
  60469. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60470. if (!this._geometry) {
  60471. return this;
  60472. }
  60473. // VBOs
  60474. this._geometry._bind(this._colorShader.getEffect());
  60475. // Color
  60476. if (!this.useVertexColor) {
  60477. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60478. }
  60479. return this;
  60480. };
  60481. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60482. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60483. return this;
  60484. }
  60485. var engine = this.getScene().getEngine();
  60486. // Draw order
  60487. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60488. return this;
  60489. };
  60490. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60491. this._colorShader.dispose();
  60492. _super.prototype.dispose.call(this, doNotRecurse);
  60493. };
  60494. /**
  60495. * Returns a new LineMesh object cloned from the current one.
  60496. */
  60497. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60498. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60499. };
  60500. return LinesMesh;
  60501. }(BABYLON.Mesh));
  60502. BABYLON.LinesMesh = LinesMesh;
  60503. })(BABYLON || (BABYLON = {}));
  60504. //# sourceMappingURL=babylon.linesMesh.js.map
  60505. var BABYLON;
  60506. (function (BABYLON) {
  60507. /**
  60508. * Class containing static functions to help procedurally build meshes
  60509. */
  60510. var MeshBuilder = /** @class */ (function () {
  60511. function MeshBuilder() {
  60512. }
  60513. MeshBuilder.updateSideOrientation = function (orientation) {
  60514. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60515. return BABYLON.Mesh.DOUBLESIDE;
  60516. }
  60517. if (orientation === undefined || orientation === null) {
  60518. return BABYLON.Mesh.FRONTSIDE;
  60519. }
  60520. return orientation;
  60521. };
  60522. /**
  60523. * Creates a box mesh
  60524. * * The parameter `size` sets the size (float) of each box side (default 1)
  60525. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60526. * * 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)
  60527. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60528. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60529. * * 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
  60530. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60531. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60532. * @param name defines the name of the mesh
  60533. * @param options defines the options used to create the mesh
  60534. * @param scene defines the hosting scene
  60535. * @returns the box mesh
  60536. */
  60537. MeshBuilder.CreateBox = function (name, options, scene) {
  60538. if (scene === void 0) { scene = null; }
  60539. var box = new BABYLON.Mesh(name, scene);
  60540. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60541. box._originalBuilderSideOrientation = options.sideOrientation;
  60542. var vertexData = BABYLON.VertexData.CreateBox(options);
  60543. vertexData.applyToMesh(box, options.updatable);
  60544. return box;
  60545. };
  60546. /**
  60547. * Creates a sphere mesh
  60548. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60549. * * 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`)
  60550. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60551. * * 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
  60552. * * 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)
  60553. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60554. * * 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
  60555. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60556. * @param name defines the name of the mesh
  60557. * @param options defines the options used to create the mesh
  60558. * @param scene defines the hosting scene
  60559. * @returns the sphere mesh
  60560. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60561. */
  60562. MeshBuilder.CreateSphere = function (name, options, scene) {
  60563. var sphere = new BABYLON.Mesh(name, scene);
  60564. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60565. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60566. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60567. vertexData.applyToMesh(sphere, options.updatable);
  60568. return sphere;
  60569. };
  60570. /**
  60571. * Creates a plane polygonal mesh. By default, this is a disc
  60572. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60573. * * 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
  60574. * * 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
  60575. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60576. * * 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
  60577. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60578. * @param name defines the name of the mesh
  60579. * @param options defines the options used to create the mesh
  60580. * @param scene defines the hosting scene
  60581. * @returns the plane polygonal mesh
  60582. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60583. */
  60584. MeshBuilder.CreateDisc = function (name, options, scene) {
  60585. if (scene === void 0) { scene = null; }
  60586. var disc = new BABYLON.Mesh(name, scene);
  60587. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60588. disc._originalBuilderSideOrientation = options.sideOrientation;
  60589. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60590. vertexData.applyToMesh(disc, options.updatable);
  60591. return disc;
  60592. };
  60593. /**
  60594. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60595. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60596. * * 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`)
  60597. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60598. * * 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
  60599. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60600. * * 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
  60601. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60602. * @param name defines the name of the mesh
  60603. * @param options defines the options used to create the mesh
  60604. * @param scene defines the hosting scene
  60605. * @returns the icosahedron mesh
  60606. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60607. */
  60608. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60609. var sphere = new BABYLON.Mesh(name, scene);
  60610. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60611. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60612. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60613. vertexData.applyToMesh(sphere, options.updatable);
  60614. return sphere;
  60615. };
  60616. ;
  60617. /**
  60618. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60619. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60620. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60621. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60622. * * 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
  60623. * * 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
  60624. * * 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
  60625. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60626. * * 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
  60627. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60628. * * 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
  60629. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60630. * * 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
  60631. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60632. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60633. * @param name defines the name of the mesh
  60634. * @param options defines the options used to create the mesh
  60635. * @param scene defines the hosting scene
  60636. * @returns the ribbon mesh
  60637. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60638. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60639. */
  60640. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60641. if (scene === void 0) { scene = null; }
  60642. var pathArray = options.pathArray;
  60643. var closeArray = options.closeArray;
  60644. var closePath = options.closePath;
  60645. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60646. var instance = options.instance;
  60647. var updatable = options.updatable;
  60648. if (instance) { // existing ribbon instance update
  60649. // positionFunction : ribbon case
  60650. // only pathArray and sideOrientation parameters are taken into account for positions update
  60651. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60652. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60653. var positionFunction = function (positions) {
  60654. var minlg = pathArray[0].length;
  60655. var i = 0;
  60656. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60657. for (var si = 1; si <= ns; si++) {
  60658. for (var p = 0; p < pathArray.length; p++) {
  60659. var path = pathArray[p];
  60660. var l = path.length;
  60661. minlg = (minlg < l) ? minlg : l;
  60662. var j = 0;
  60663. while (j < minlg) {
  60664. positions[i] = path[j].x;
  60665. positions[i + 1] = path[j].y;
  60666. positions[i + 2] = path[j].z;
  60667. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60668. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60669. }
  60670. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60671. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60672. }
  60673. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60674. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60675. }
  60676. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60677. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60678. }
  60679. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60680. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60681. }
  60682. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60683. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60684. }
  60685. j++;
  60686. i += 3;
  60687. }
  60688. if (instance._closePath) {
  60689. positions[i] = path[0].x;
  60690. positions[i + 1] = path[0].y;
  60691. positions[i + 2] = path[0].z;
  60692. i += 3;
  60693. }
  60694. }
  60695. }
  60696. };
  60697. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60698. positionFunction(positions);
  60699. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60700. instance._boundingInfo.update(instance._worldMatrix);
  60701. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60702. if (options.colors) {
  60703. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60704. for (var c = 0; c < options.colors.length; c++) {
  60705. colors[c * 4] = options.colors[c].r;
  60706. colors[c * 4 + 1] = options.colors[c].g;
  60707. colors[c * 4 + 2] = options.colors[c].b;
  60708. colors[c * 4 + 3] = options.colors[c].a;
  60709. }
  60710. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60711. }
  60712. if (options.uvs) {
  60713. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60714. for (var i = 0; i < options.uvs.length; i++) {
  60715. uvs[i * 2] = options.uvs[i].x;
  60716. uvs[i * 2 + 1] = options.uvs[i].y;
  60717. }
  60718. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60719. }
  60720. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60721. var indices = instance.getIndices();
  60722. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60723. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60724. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60725. if (instance._closePath) {
  60726. var indexFirst = 0;
  60727. var indexLast = 0;
  60728. for (var p = 0; p < pathArray.length; p++) {
  60729. indexFirst = instance._idx[p] * 3;
  60730. if (p + 1 < pathArray.length) {
  60731. indexLast = (instance._idx[p + 1] - 1) * 3;
  60732. }
  60733. else {
  60734. indexLast = normals.length - 3;
  60735. }
  60736. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60737. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60738. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60739. normals[indexLast] = normals[indexFirst];
  60740. normals[indexLast + 1] = normals[indexFirst + 1];
  60741. normals[indexLast + 2] = normals[indexFirst + 2];
  60742. }
  60743. }
  60744. if (!(instance.areNormalsFrozen)) {
  60745. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60746. }
  60747. }
  60748. return instance;
  60749. }
  60750. else { // new ribbon creation
  60751. var ribbon = new BABYLON.Mesh(name, scene);
  60752. ribbon._originalBuilderSideOrientation = sideOrientation;
  60753. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60754. if (closePath) {
  60755. ribbon._idx = vertexData._idx;
  60756. }
  60757. ribbon._closePath = closePath;
  60758. ribbon._closeArray = closeArray;
  60759. vertexData.applyToMesh(ribbon, updatable);
  60760. return ribbon;
  60761. }
  60762. };
  60763. /**
  60764. * Creates a cylinder or a cone mesh
  60765. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60766. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60767. * * 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.
  60768. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60769. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60770. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60771. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60772. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60773. * * 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).
  60774. * * 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
  60775. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60776. * * 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
  60777. * * 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.
  60778. * * If `enclose` is false, a ring surface is one element.
  60779. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60780. * * 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
  60781. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60782. * * 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
  60783. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60784. * @param name defines the name of the mesh
  60785. * @param options defines the options used to create the mesh
  60786. * @param scene defines the hosting scene
  60787. * @returns the cylinder mesh
  60788. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60789. */
  60790. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60791. var cylinder = new BABYLON.Mesh(name, scene);
  60792. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60793. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60794. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60795. vertexData.applyToMesh(cylinder, options.updatable);
  60796. return cylinder;
  60797. };
  60798. /**
  60799. * Creates a torus mesh
  60800. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60801. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60802. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60803. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60804. * * 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
  60805. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60806. * @param name defines the name of the mesh
  60807. * @param options defines the options used to create the mesh
  60808. * @param scene defines the hosting scene
  60809. * @returns the torus mesh
  60810. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60811. */
  60812. MeshBuilder.CreateTorus = function (name, options, scene) {
  60813. var torus = new BABYLON.Mesh(name, scene);
  60814. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60815. torus._originalBuilderSideOrientation = options.sideOrientation;
  60816. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60817. vertexData.applyToMesh(torus, options.updatable);
  60818. return torus;
  60819. };
  60820. /**
  60821. * Creates a torus knot mesh
  60822. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60823. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60824. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60825. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60826. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60827. * * 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
  60828. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60829. * @param name defines the name of the mesh
  60830. * @param options defines the options used to create the mesh
  60831. * @param scene defines the hosting scene
  60832. * @returns the torus knot mesh
  60833. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60834. */
  60835. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60836. var torusKnot = new BABYLON.Mesh(name, scene);
  60837. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60838. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60839. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60840. vertexData.applyToMesh(torusKnot, options.updatable);
  60841. return torusKnot;
  60842. };
  60843. /**
  60844. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60845. * * 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
  60846. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60847. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60848. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60849. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60850. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60851. * * 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
  60852. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60853. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60854. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60855. * @param name defines the name of the new line system
  60856. * @param options defines the options used to create the line system
  60857. * @param scene defines the hosting scene
  60858. * @returns a new line system mesh
  60859. */
  60860. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60861. var instance = options.instance;
  60862. var lines = options.lines;
  60863. var colors = options.colors;
  60864. if (instance) { // lines update
  60865. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60866. var vertexColor;
  60867. var lineColors;
  60868. if (colors) {
  60869. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60870. }
  60871. var i = 0;
  60872. var c = 0;
  60873. for (var l = 0; l < lines.length; l++) {
  60874. var points = lines[l];
  60875. for (var p = 0; p < points.length; p++) {
  60876. positions[i] = points[p].x;
  60877. positions[i + 1] = points[p].y;
  60878. positions[i + 2] = points[p].z;
  60879. if (colors && vertexColor) {
  60880. lineColors = colors[l];
  60881. vertexColor[c] = lineColors[p].r;
  60882. vertexColor[c + 1] = lineColors[p].g;
  60883. vertexColor[c + 2] = lineColors[p].b;
  60884. vertexColor[c + 3] = lineColors[p].a;
  60885. c += 4;
  60886. }
  60887. i += 3;
  60888. }
  60889. }
  60890. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60891. if (colors && vertexColor) {
  60892. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60893. }
  60894. return instance;
  60895. }
  60896. // line system creation
  60897. var useVertexColor = (colors) ? true : false;
  60898. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60899. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60900. vertexData.applyToMesh(lineSystem, options.updatable);
  60901. return lineSystem;
  60902. };
  60903. /**
  60904. * Creates a line mesh
  60905. * 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
  60906. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60907. * * The parameter `points` is an array successive Vector3
  60908. * * 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
  60909. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60910. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60911. * * When updating an instance, remember that only point positions can change, not the number of points
  60912. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60913. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60914. * @param name defines the name of the new line system
  60915. * @param options defines the options used to create the line system
  60916. * @param scene defines the hosting scene
  60917. * @returns a new line mesh
  60918. */
  60919. MeshBuilder.CreateLines = function (name, options, scene) {
  60920. if (scene === void 0) { scene = null; }
  60921. var colors = (options.colors) ? [options.colors] : null;
  60922. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60923. return lines;
  60924. };
  60925. /**
  60926. * Creates a dashed line mesh
  60927. * * 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
  60928. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60929. * * The parameter `points` is an array successive Vector3
  60930. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60931. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60932. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60933. * * 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
  60934. * * When updating an instance, remember that only point positions can change, not the number of points
  60935. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60936. * @param name defines the name of the mesh
  60937. * @param options defines the options used to create the mesh
  60938. * @param scene defines the hosting scene
  60939. * @returns the dashed line mesh
  60940. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60941. */
  60942. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60943. if (scene === void 0) { scene = null; }
  60944. var points = options.points;
  60945. var instance = options.instance;
  60946. var gapSize = options.gapSize || 1;
  60947. var dashSize = options.dashSize || 3;
  60948. if (instance) { // dashed lines update
  60949. var positionFunction = function (positions) {
  60950. var curvect = BABYLON.Vector3.Zero();
  60951. var nbSeg = positions.length / 6;
  60952. var lg = 0;
  60953. var nb = 0;
  60954. var shft = 0;
  60955. var dashshft = 0;
  60956. var curshft = 0;
  60957. var p = 0;
  60958. var i = 0;
  60959. var j = 0;
  60960. for (i = 0; i < points.length - 1; i++) {
  60961. points[i + 1].subtractToRef(points[i], curvect);
  60962. lg += curvect.length();
  60963. }
  60964. shft = lg / nbSeg;
  60965. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60966. for (i = 0; i < points.length - 1; i++) {
  60967. points[i + 1].subtractToRef(points[i], curvect);
  60968. nb = Math.floor(curvect.length() / shft);
  60969. curvect.normalize();
  60970. j = 0;
  60971. while (j < nb && p < positions.length) {
  60972. curshft = shft * j;
  60973. positions[p] = points[i].x + curshft * curvect.x;
  60974. positions[p + 1] = points[i].y + curshft * curvect.y;
  60975. positions[p + 2] = points[i].z + curshft * curvect.z;
  60976. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60977. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60978. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60979. p += 6;
  60980. j++;
  60981. }
  60982. }
  60983. while (p < positions.length) {
  60984. positions[p] = points[i].x;
  60985. positions[p + 1] = points[i].y;
  60986. positions[p + 2] = points[i].z;
  60987. p += 3;
  60988. }
  60989. };
  60990. instance.updateMeshPositions(positionFunction, false);
  60991. return instance;
  60992. }
  60993. // dashed lines creation
  60994. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60995. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60996. vertexData.applyToMesh(dashedLines, options.updatable);
  60997. dashedLines.dashSize = dashSize;
  60998. dashedLines.gapSize = gapSize;
  60999. return dashedLines;
  61000. };
  61001. /**
  61002. * 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.
  61003. * * 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.
  61004. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61005. * * 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.
  61006. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61007. * * 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
  61008. * * 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
  61009. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61010. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61011. * * 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
  61012. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61013. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61014. * @param name defines the name of the mesh
  61015. * @param options defines the options used to create the mesh
  61016. * @param scene defines the hosting scene
  61017. * @returns the extruded shape mesh
  61018. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61019. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61020. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61021. */
  61022. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61023. if (scene === void 0) { scene = null; }
  61024. var path = options.path;
  61025. var shape = options.shape;
  61026. var scale = options.scale || 1;
  61027. var rotation = options.rotation || 0;
  61028. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61029. var updatable = options.updatable;
  61030. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61031. var instance = options.instance || null;
  61032. var invertUV = options.invertUV || false;
  61033. 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);
  61034. };
  61035. /**
  61036. * Creates an custom extruded shape mesh.
  61037. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61038. * * 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.
  61039. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61040. * * 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
  61041. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61042. * * 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
  61043. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61044. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61045. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61046. * * 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
  61047. * * 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
  61048. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61049. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61050. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61051. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61052. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61053. * @param name defines the name of the mesh
  61054. * @param options defines the options used to create the mesh
  61055. * @param scene defines the hosting scene
  61056. * @returns the custom extruded shape mesh
  61057. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61058. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61059. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61060. */
  61061. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61062. var path = options.path;
  61063. var shape = options.shape;
  61064. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61065. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61066. var ribbonCloseArray = options.ribbonCloseArray || false;
  61067. var ribbonClosePath = options.ribbonClosePath || false;
  61068. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61069. var updatable = options.updatable;
  61070. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61071. var instance = options.instance;
  61072. var invertUV = options.invertUV || false;
  61073. 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);
  61074. };
  61075. /**
  61076. * Creates lathe mesh.
  61077. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61078. * * 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
  61079. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61080. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61081. * * 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
  61082. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61083. * * 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
  61084. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61085. * * 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
  61086. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61087. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61088. * @param name defines the name of the mesh
  61089. * @param options defines the options used to create the mesh
  61090. * @param scene defines the hosting scene
  61091. * @returns the lathe mesh
  61092. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61093. */
  61094. MeshBuilder.CreateLathe = function (name, options, scene) {
  61095. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61096. var closed = (options.closed === undefined) ? true : options.closed;
  61097. var shape = options.shape;
  61098. var radius = options.radius || 1;
  61099. var tessellation = options.tessellation || 64;
  61100. var updatable = options.updatable;
  61101. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61102. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61103. var pi2 = Math.PI * 2;
  61104. var paths = new Array();
  61105. var invertUV = options.invertUV || false;
  61106. var i = 0;
  61107. var p = 0;
  61108. var step = pi2 / tessellation * arc;
  61109. var rotated;
  61110. var path = new Array();
  61111. for (i = 0; i <= tessellation; i++) {
  61112. var path = [];
  61113. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61114. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61115. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61116. }
  61117. for (p = 0; p < shape.length; p++) {
  61118. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61119. path.push(rotated);
  61120. }
  61121. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61122. 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));
  61123. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61124. }
  61125. paths.push(path);
  61126. }
  61127. // lathe ribbon
  61128. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61129. return lathe;
  61130. };
  61131. /**
  61132. * Creates a plane mesh
  61133. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61134. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61135. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61136. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61137. * * 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
  61138. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61139. * @param name defines the name of the mesh
  61140. * @param options defines the options used to create the mesh
  61141. * @param scene defines the hosting scene
  61142. * @returns the plane mesh
  61143. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61144. */
  61145. MeshBuilder.CreatePlane = function (name, options, scene) {
  61146. var plane = new BABYLON.Mesh(name, scene);
  61147. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61148. plane._originalBuilderSideOrientation = options.sideOrientation;
  61149. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61150. vertexData.applyToMesh(plane, options.updatable);
  61151. if (options.sourcePlane) {
  61152. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61153. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61154. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61155. plane.rotate(vectorProduct, product);
  61156. }
  61157. return plane;
  61158. };
  61159. /**
  61160. * Creates a ground mesh
  61161. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61162. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61163. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61164. * @param name defines the name of the mesh
  61165. * @param options defines the options used to create the mesh
  61166. * @param scene defines the hosting scene
  61167. * @returns the ground mesh
  61168. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61169. */
  61170. MeshBuilder.CreateGround = function (name, options, scene) {
  61171. var ground = new BABYLON.GroundMesh(name, scene);
  61172. ground._setReady(false);
  61173. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61174. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61175. ground._width = options.width || 1;
  61176. ground._height = options.height || 1;
  61177. ground._maxX = ground._width / 2;
  61178. ground._maxZ = ground._height / 2;
  61179. ground._minX = -ground._maxX;
  61180. ground._minZ = -ground._maxZ;
  61181. var vertexData = BABYLON.VertexData.CreateGround(options);
  61182. vertexData.applyToMesh(ground, options.updatable);
  61183. ground._setReady(true);
  61184. return ground;
  61185. };
  61186. /**
  61187. * Creates a tiled ground mesh
  61188. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61189. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61190. * * 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
  61191. * * 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
  61192. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61193. * @param name defines the name of the mesh
  61194. * @param options defines the options used to create the mesh
  61195. * @param scene defines the hosting scene
  61196. * @returns the tiled ground mesh
  61197. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61198. */
  61199. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61200. var tiledGround = new BABYLON.Mesh(name, scene);
  61201. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61202. vertexData.applyToMesh(tiledGround, options.updatable);
  61203. return tiledGround;
  61204. };
  61205. /**
  61206. * Creates a ground mesh from a height map
  61207. * * The parameter `url` sets the URL of the height map image resource.
  61208. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61209. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61210. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61211. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61212. * * 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.
  61213. * * 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).
  61214. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61215. * @param name defines the name of the mesh
  61216. * @param url defines the url to the height map
  61217. * @param options defines the options used to create the mesh
  61218. * @param scene defines the hosting scene
  61219. * @returns the ground mesh
  61220. * @see http://doc.babylonjs.com/babylon101/height_map
  61221. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61222. */
  61223. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61224. var width = options.width || 10.0;
  61225. var height = options.height || 10.0;
  61226. var subdivisions = options.subdivisions || 1 | 0;
  61227. var minHeight = options.minHeight || 0.0;
  61228. var maxHeight = options.maxHeight || 1.0;
  61229. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61230. var updatable = options.updatable;
  61231. var onReady = options.onReady;
  61232. var ground = new BABYLON.GroundMesh(name, scene);
  61233. ground._subdivisionsX = subdivisions;
  61234. ground._subdivisionsY = subdivisions;
  61235. ground._width = width;
  61236. ground._height = height;
  61237. ground._maxX = ground._width / 2.0;
  61238. ground._maxZ = ground._height / 2.0;
  61239. ground._minX = -ground._maxX;
  61240. ground._minZ = -ground._maxZ;
  61241. ground._setReady(false);
  61242. var onload = function (img) {
  61243. // Getting height map data
  61244. var canvas = document.createElement("canvas");
  61245. var context = canvas.getContext("2d");
  61246. if (!context) {
  61247. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61248. }
  61249. if (scene.isDisposed) {
  61250. return;
  61251. }
  61252. var bufferWidth = img.width;
  61253. var bufferHeight = img.height;
  61254. canvas.width = bufferWidth;
  61255. canvas.height = bufferHeight;
  61256. context.drawImage(img, 0, 0);
  61257. // Create VertexData from map data
  61258. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61259. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61260. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61261. width: width, height: height,
  61262. subdivisions: subdivisions,
  61263. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61264. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61265. });
  61266. vertexData.applyToMesh(ground, updatable);
  61267. //execute ready callback, if set
  61268. if (onReady) {
  61269. onReady(ground);
  61270. }
  61271. ground._setReady(true);
  61272. };
  61273. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61274. return ground;
  61275. };
  61276. /**
  61277. * Creates a polygon mesh
  61278. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61279. * * 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
  61280. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61281. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61282. * * 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)
  61283. * * Remember you can only change the shape positions, not their number when updating a polygon
  61284. * @param name defines the name of the mesh
  61285. * @param options defines the options used to create the mesh
  61286. * @param scene defines the hosting scene
  61287. * @returns the polygon mesh
  61288. */
  61289. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61290. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61291. var shape = options.shape;
  61292. var holes = options.holes || [];
  61293. var depth = options.depth || 0;
  61294. var contours = [];
  61295. var hole = [];
  61296. for (var i = 0; i < shape.length; i++) {
  61297. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61298. }
  61299. var epsilon = 0.00000001;
  61300. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61301. contours.pop();
  61302. }
  61303. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61304. for (var hNb = 0; hNb < holes.length; hNb++) {
  61305. hole = [];
  61306. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61307. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61308. }
  61309. polygonTriangulation.addHole(hole);
  61310. }
  61311. var polygon = polygonTriangulation.build(options.updatable, depth);
  61312. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61313. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61314. vertexData.applyToMesh(polygon, options.updatable);
  61315. return polygon;
  61316. };
  61317. ;
  61318. /**
  61319. * Creates an extruded polygon mesh, with depth in the Y direction.
  61320. * * 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)
  61321. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61322. * @param name defines the name of the mesh
  61323. * @param options defines the options used to create the mesh
  61324. * @param scene defines the hosting scene
  61325. * @returns the polygon mesh
  61326. */
  61327. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61328. return MeshBuilder.CreatePolygon(name, options, scene);
  61329. };
  61330. ;
  61331. /**
  61332. * Creates a tube mesh.
  61333. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61334. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61335. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61336. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61337. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61338. * * 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)
  61339. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61340. * * 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
  61341. * * 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
  61342. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61343. * * 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
  61344. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61345. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61346. * @param name defines the name of the mesh
  61347. * @param options defines the options used to create the mesh
  61348. * @param scene defines the hosting scene
  61349. * @returns the tube mesh
  61350. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61351. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61352. */
  61353. MeshBuilder.CreateTube = function (name, options, scene) {
  61354. var path = options.path;
  61355. var instance = options.instance;
  61356. var radius = 1.0;
  61357. if (instance) {
  61358. radius = instance.radius;
  61359. }
  61360. if (options.radius !== undefined) {
  61361. radius = options.radius;
  61362. }
  61363. ;
  61364. var tessellation = options.tessellation || 64 | 0;
  61365. var radiusFunction = options.radiusFunction || null;
  61366. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61367. var invertUV = options.invertUV || false;
  61368. var updatable = options.updatable;
  61369. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61370. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61371. // tube geometry
  61372. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61373. var tangents = path3D.getTangents();
  61374. var normals = path3D.getNormals();
  61375. var distances = path3D.getDistances();
  61376. var pi2 = Math.PI * 2;
  61377. var step = pi2 / tessellation * arc;
  61378. var returnRadius = function () { return radius; };
  61379. var radiusFunctionFinal = radiusFunction || returnRadius;
  61380. var circlePath;
  61381. var rad;
  61382. var normal;
  61383. var rotated;
  61384. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61385. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61386. for (var i = 0; i < path.length; i++) {
  61387. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61388. circlePath = Array(); // current circle array
  61389. normal = normals[i]; // current normal
  61390. for (var t = 0; t < tessellation; t++) {
  61391. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61392. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61393. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61394. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61395. circlePath[t] = rotated;
  61396. }
  61397. circlePaths[index] = circlePath;
  61398. index++;
  61399. }
  61400. // cap
  61401. var capPath = function (nbPoints, pathIndex) {
  61402. var pointCap = Array();
  61403. for (var i = 0; i < nbPoints; i++) {
  61404. pointCap.push(path[pathIndex]);
  61405. }
  61406. return pointCap;
  61407. };
  61408. switch (cap) {
  61409. case BABYLON.Mesh.NO_CAP:
  61410. break;
  61411. case BABYLON.Mesh.CAP_START:
  61412. circlePaths[0] = capPath(tessellation, 0);
  61413. circlePaths[1] = circlePaths[2].slice(0);
  61414. break;
  61415. case BABYLON.Mesh.CAP_END:
  61416. circlePaths[index] = circlePaths[index - 1].slice(0);
  61417. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61418. break;
  61419. case BABYLON.Mesh.CAP_ALL:
  61420. circlePaths[0] = capPath(tessellation, 0);
  61421. circlePaths[1] = circlePaths[2].slice(0);
  61422. circlePaths[index] = circlePaths[index - 1].slice(0);
  61423. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61424. break;
  61425. default:
  61426. break;
  61427. }
  61428. return circlePaths;
  61429. };
  61430. var path3D;
  61431. var pathArray;
  61432. if (instance) { // tube update
  61433. var arc = options.arc || instance.arc;
  61434. path3D = (instance.path3D).update(path);
  61435. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61436. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61437. instance.path3D = path3D;
  61438. instance.pathArray = pathArray;
  61439. instance.arc = arc;
  61440. instance.radius = radius;
  61441. return instance;
  61442. }
  61443. // tube creation
  61444. path3D = new BABYLON.Path3D(path);
  61445. var newPathArray = new Array();
  61446. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61447. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61448. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61449. tube.pathArray = pathArray;
  61450. tube.path3D = path3D;
  61451. tube.tessellation = tessellation;
  61452. tube.cap = cap;
  61453. tube.arc = options.arc;
  61454. tube.radius = radius;
  61455. return tube;
  61456. };
  61457. /**
  61458. * Creates a polyhedron mesh
  61459. * * 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
  61460. * * The parameter `size` (positive float, default 1) sets the polygon size
  61461. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61462. * * 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`
  61463. * * 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
  61464. * * 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)`)
  61465. * * 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
  61466. * * 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
  61467. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61468. * * 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
  61469. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61470. * @param name defines the name of the mesh
  61471. * @param options defines the options used to create the mesh
  61472. * @param scene defines the hosting scene
  61473. * @returns the polyhedron mesh
  61474. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61475. */
  61476. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61477. var polyhedron = new BABYLON.Mesh(name, scene);
  61478. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61479. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61480. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61481. vertexData.applyToMesh(polyhedron, options.updatable);
  61482. return polyhedron;
  61483. };
  61484. /**
  61485. * Creates a decal mesh.
  61486. * 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
  61487. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61488. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61489. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61490. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61491. * @param name defines the name of the mesh
  61492. * @param sourceMesh defines the mesh where the decal must be applied
  61493. * @param options defines the options used to create the mesh
  61494. * @param scene defines the hosting scene
  61495. * @returns the decal mesh
  61496. * @see http://doc.babylonjs.com/how_to/decals
  61497. */
  61498. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61499. var indices = sourceMesh.getIndices();
  61500. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61501. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61502. var position = options.position || BABYLON.Vector3.Zero();
  61503. var normal = options.normal || BABYLON.Vector3.Up();
  61504. var size = options.size || BABYLON.Vector3.One();
  61505. var angle = options.angle || 0;
  61506. // Getting correct rotation
  61507. if (!normal) {
  61508. var target = new BABYLON.Vector3(0, 0, 1);
  61509. var camera = sourceMesh.getScene().activeCamera;
  61510. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61511. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61512. }
  61513. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61514. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61515. var pitch = Math.atan2(normal.y, len);
  61516. // Matrix
  61517. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61518. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61519. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61520. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61521. var vertexData = new BABYLON.VertexData();
  61522. vertexData.indices = [];
  61523. vertexData.positions = [];
  61524. vertexData.normals = [];
  61525. vertexData.uvs = [];
  61526. var currentVertexDataIndex = 0;
  61527. var extractDecalVector3 = function (indexId) {
  61528. var result = new BABYLON.PositionNormalVertex();
  61529. if (!indices || !positions || !normals) {
  61530. return result;
  61531. }
  61532. var vertexId = indices[indexId];
  61533. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61534. // Send vector to decal local world
  61535. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61536. // Get normal
  61537. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61538. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61539. return result;
  61540. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61541. var clip = function (vertices, axis) {
  61542. if (vertices.length === 0) {
  61543. return vertices;
  61544. }
  61545. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61546. var clipVertices = function (v0, v1) {
  61547. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61548. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61549. };
  61550. var result = new Array();
  61551. for (var index = 0; index < vertices.length; index += 3) {
  61552. var v1Out;
  61553. var v2Out;
  61554. var v3Out;
  61555. var total = 0;
  61556. var nV1 = null;
  61557. var nV2 = null;
  61558. var nV3 = null;
  61559. var nV4 = null;
  61560. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61561. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61562. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61563. v1Out = d1 > 0;
  61564. v2Out = d2 > 0;
  61565. v3Out = d3 > 0;
  61566. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61567. switch (total) {
  61568. case 0:
  61569. result.push(vertices[index]);
  61570. result.push(vertices[index + 1]);
  61571. result.push(vertices[index + 2]);
  61572. break;
  61573. case 1:
  61574. if (v1Out) {
  61575. nV1 = vertices[index + 1];
  61576. nV2 = vertices[index + 2];
  61577. nV3 = clipVertices(vertices[index], nV1);
  61578. nV4 = clipVertices(vertices[index], nV2);
  61579. }
  61580. if (v2Out) {
  61581. nV1 = vertices[index];
  61582. nV2 = vertices[index + 2];
  61583. nV3 = clipVertices(vertices[index + 1], nV1);
  61584. nV4 = clipVertices(vertices[index + 1], nV2);
  61585. result.push(nV3);
  61586. result.push(nV2.clone());
  61587. result.push(nV1.clone());
  61588. result.push(nV2.clone());
  61589. result.push(nV3.clone());
  61590. result.push(nV4);
  61591. break;
  61592. }
  61593. if (v3Out) {
  61594. nV1 = vertices[index];
  61595. nV2 = vertices[index + 1];
  61596. nV3 = clipVertices(vertices[index + 2], nV1);
  61597. nV4 = clipVertices(vertices[index + 2], nV2);
  61598. }
  61599. if (nV1 && nV2 && nV3 && nV4) {
  61600. result.push(nV1.clone());
  61601. result.push(nV2.clone());
  61602. result.push(nV3);
  61603. result.push(nV4);
  61604. result.push(nV3.clone());
  61605. result.push(nV2.clone());
  61606. }
  61607. break;
  61608. case 2:
  61609. if (!v1Out) {
  61610. nV1 = vertices[index].clone();
  61611. nV2 = clipVertices(nV1, vertices[index + 1]);
  61612. nV3 = clipVertices(nV1, vertices[index + 2]);
  61613. result.push(nV1);
  61614. result.push(nV2);
  61615. result.push(nV3);
  61616. }
  61617. if (!v2Out) {
  61618. nV1 = vertices[index + 1].clone();
  61619. nV2 = clipVertices(nV1, vertices[index + 2]);
  61620. nV3 = clipVertices(nV1, vertices[index]);
  61621. result.push(nV1);
  61622. result.push(nV2);
  61623. result.push(nV3);
  61624. }
  61625. if (!v3Out) {
  61626. nV1 = vertices[index + 2].clone();
  61627. nV2 = clipVertices(nV1, vertices[index]);
  61628. nV3 = clipVertices(nV1, vertices[index + 1]);
  61629. result.push(nV1);
  61630. result.push(nV2);
  61631. result.push(nV3);
  61632. }
  61633. break;
  61634. case 3:
  61635. break;
  61636. }
  61637. }
  61638. return result;
  61639. };
  61640. for (var index = 0; index < indices.length; index += 3) {
  61641. var faceVertices = new Array();
  61642. faceVertices.push(extractDecalVector3(index));
  61643. faceVertices.push(extractDecalVector3(index + 1));
  61644. faceVertices.push(extractDecalVector3(index + 2));
  61645. // Clip
  61646. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61647. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61648. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61649. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61650. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61651. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61652. if (faceVertices.length === 0) {
  61653. continue;
  61654. }
  61655. // Add UVs and get back to world
  61656. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61657. var vertex = faceVertices[vIndex];
  61658. //TODO check for Int32Array | Uint32Array | Uint16Array
  61659. vertexData.indices.push(currentVertexDataIndex);
  61660. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61661. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61662. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61663. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61664. currentVertexDataIndex++;
  61665. }
  61666. }
  61667. // Return mesh
  61668. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61669. vertexData.applyToMesh(decal);
  61670. decal.position = position.clone();
  61671. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61672. return decal;
  61673. };
  61674. // Privates
  61675. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61676. // extrusion geometry
  61677. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61678. var tangents = path3D.getTangents();
  61679. var normals = path3D.getNormals();
  61680. var binormals = path3D.getBinormals();
  61681. var distances = path3D.getDistances();
  61682. var angle = 0;
  61683. var returnScale = function () { return scale !== null ? scale : 1; };
  61684. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61685. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61686. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61687. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61688. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61689. for (var i = 0; i < curve.length; i++) {
  61690. var shapePath = new Array();
  61691. var angleStep = rotate(i, distances[i]);
  61692. var scaleRatio = scl(i, distances[i]);
  61693. for (var p = 0; p < shape.length; p++) {
  61694. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61695. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61696. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61697. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61698. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61699. shapePath[p] = rotated;
  61700. }
  61701. shapePaths[index] = shapePath;
  61702. angle += angleStep;
  61703. index++;
  61704. }
  61705. // cap
  61706. var capPath = function (shapePath) {
  61707. var pointCap = Array();
  61708. var barycenter = BABYLON.Vector3.Zero();
  61709. var i;
  61710. for (i = 0; i < shapePath.length; i++) {
  61711. barycenter.addInPlace(shapePath[i]);
  61712. }
  61713. barycenter.scaleInPlace(1.0 / shapePath.length);
  61714. for (i = 0; i < shapePath.length; i++) {
  61715. pointCap.push(barycenter);
  61716. }
  61717. return pointCap;
  61718. };
  61719. switch (cap) {
  61720. case BABYLON.Mesh.NO_CAP:
  61721. break;
  61722. case BABYLON.Mesh.CAP_START:
  61723. shapePaths[0] = capPath(shapePaths[2]);
  61724. shapePaths[1] = shapePaths[2];
  61725. break;
  61726. case BABYLON.Mesh.CAP_END:
  61727. shapePaths[index] = shapePaths[index - 1];
  61728. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61729. break;
  61730. case BABYLON.Mesh.CAP_ALL:
  61731. shapePaths[0] = capPath(shapePaths[2]);
  61732. shapePaths[1] = shapePaths[2];
  61733. shapePaths[index] = shapePaths[index - 1];
  61734. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61735. break;
  61736. default:
  61737. break;
  61738. }
  61739. return shapePaths;
  61740. };
  61741. var path3D;
  61742. var pathArray;
  61743. if (instance) { // instance update
  61744. path3D = (instance.path3D).update(curve);
  61745. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61746. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61747. return instance;
  61748. }
  61749. // extruded shape creation
  61750. path3D = new BABYLON.Path3D(curve);
  61751. var newShapePaths = new Array();
  61752. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61753. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61754. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61755. extrudedGeneric.pathArray = pathArray;
  61756. extrudedGeneric.path3D = path3D;
  61757. extrudedGeneric.cap = cap;
  61758. return extrudedGeneric;
  61759. };
  61760. return MeshBuilder;
  61761. }());
  61762. BABYLON.MeshBuilder = MeshBuilder;
  61763. })(BABYLON || (BABYLON = {}));
  61764. //# sourceMappingURL=babylon.meshBuilder.js.map
  61765. var BABYLON;
  61766. (function (BABYLON) {
  61767. /**
  61768. * Draco compression (https://google.github.io/draco/)
  61769. */
  61770. var DracoCompression = /** @class */ (function () {
  61771. /**
  61772. * Constructor
  61773. */
  61774. function DracoCompression() {
  61775. }
  61776. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61777. /**
  61778. * Returns true if the decoder is available.
  61779. */
  61780. get: function () {
  61781. if (typeof DracoDecoderModule !== "undefined") {
  61782. return true;
  61783. }
  61784. var decoder = DracoCompression.Configuration.decoder;
  61785. if (decoder) {
  61786. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61787. return true;
  61788. }
  61789. if (decoder.fallbackUrl) {
  61790. return true;
  61791. }
  61792. }
  61793. return false;
  61794. },
  61795. enumerable: true,
  61796. configurable: true
  61797. });
  61798. /**
  61799. * Stop all async operations and release resources.
  61800. */
  61801. DracoCompression.prototype.dispose = function () {
  61802. };
  61803. /**
  61804. * Decode Draco compressed mesh data to vertex data.
  61805. * @param data The array buffer view for the Draco compression data
  61806. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61807. * @returns A promise that resolves with the decoded vertex data
  61808. */
  61809. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61810. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61811. var module = wrappedModule.module;
  61812. var vertexData = new BABYLON.VertexData();
  61813. var buffer = new module.DecoderBuffer();
  61814. buffer.Init(data, data.byteLength);
  61815. var decoder = new module.Decoder();
  61816. var geometry;
  61817. var status;
  61818. try {
  61819. var type = decoder.GetEncodedGeometryType(buffer);
  61820. switch (type) {
  61821. case module.TRIANGULAR_MESH:
  61822. geometry = new module.Mesh();
  61823. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61824. break;
  61825. case module.POINT_CLOUD:
  61826. geometry = new module.PointCloud();
  61827. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61828. break;
  61829. default:
  61830. throw new Error("Invalid geometry type " + type);
  61831. }
  61832. if (!status.ok() || !geometry.ptr) {
  61833. throw new Error(status.error_msg());
  61834. }
  61835. var numPoints = geometry.num_points();
  61836. if (type === module.TRIANGULAR_MESH) {
  61837. var numFaces = geometry.num_faces();
  61838. var faceIndices = new module.DracoInt32Array();
  61839. try {
  61840. var indices = new Uint32Array(numFaces * 3);
  61841. for (var i = 0; i < numFaces; i++) {
  61842. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61843. var offset = i * 3;
  61844. indices[offset + 0] = faceIndices.GetValue(0);
  61845. indices[offset + 1] = faceIndices.GetValue(1);
  61846. indices[offset + 2] = faceIndices.GetValue(2);
  61847. }
  61848. vertexData.indices = indices;
  61849. }
  61850. finally {
  61851. module.destroy(faceIndices);
  61852. }
  61853. }
  61854. for (var kind in attributes) {
  61855. var uniqueId = attributes[kind];
  61856. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61857. var dracoData = new module.DracoFloat32Array();
  61858. try {
  61859. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61860. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61861. for (var i = 0; i < babylonData.length; i++) {
  61862. babylonData[i] = dracoData.GetValue(i);
  61863. }
  61864. vertexData.set(babylonData, kind);
  61865. }
  61866. finally {
  61867. module.destroy(dracoData);
  61868. }
  61869. }
  61870. }
  61871. finally {
  61872. if (geometry) {
  61873. module.destroy(geometry);
  61874. }
  61875. module.destroy(decoder);
  61876. module.destroy(buffer);
  61877. }
  61878. return vertexData;
  61879. });
  61880. };
  61881. DracoCompression._GetDecoderModule = function () {
  61882. if (!DracoCompression._DecoderModulePromise) {
  61883. var promise = null;
  61884. var config_1 = {};
  61885. if (typeof DracoDecoderModule !== "undefined") {
  61886. promise = Promise.resolve();
  61887. }
  61888. else {
  61889. var decoder = DracoCompression.Configuration.decoder;
  61890. if (decoder) {
  61891. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61892. promise = Promise.all([
  61893. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61894. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61895. config_1.wasmBinary = data;
  61896. })
  61897. ]);
  61898. }
  61899. else if (decoder.fallbackUrl) {
  61900. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61901. }
  61902. }
  61903. }
  61904. if (!promise) {
  61905. throw new Error("Draco decoder module is not available");
  61906. }
  61907. DracoCompression._DecoderModulePromise = promise.then(function () {
  61908. return new Promise(function (resolve) {
  61909. config_1.onModuleLoaded = function (decoderModule) {
  61910. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61911. resolve({ module: decoderModule });
  61912. };
  61913. DracoDecoderModule(config_1);
  61914. });
  61915. });
  61916. }
  61917. return DracoCompression._DecoderModulePromise;
  61918. };
  61919. DracoCompression._LoadScriptAsync = function (url) {
  61920. return new Promise(function (resolve, reject) {
  61921. BABYLON.Tools.LoadScript(url, function () {
  61922. resolve();
  61923. }, function (message) {
  61924. reject(new Error(message));
  61925. });
  61926. });
  61927. };
  61928. DracoCompression._LoadFileAsync = function (url) {
  61929. return new Promise(function (resolve, reject) {
  61930. BABYLON.Tools.LoadFile(url, function (data) {
  61931. resolve(data);
  61932. }, undefined, undefined, true, function (request, exception) {
  61933. reject(exception);
  61934. });
  61935. });
  61936. };
  61937. /**
  61938. * The configuration.
  61939. */
  61940. DracoCompression.Configuration = {
  61941. decoder: {
  61942. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61943. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61944. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61945. }
  61946. };
  61947. return DracoCompression;
  61948. }());
  61949. BABYLON.DracoCompression = DracoCompression;
  61950. })(BABYLON || (BABYLON = {}));
  61951. //# sourceMappingURL=babylon.dracoCompression.js.map
  61952. var BABYLON;
  61953. (function (BABYLON) {
  61954. var AudioEngine = /** @class */ (function () {
  61955. function AudioEngine() {
  61956. this._audioContext = null;
  61957. this._audioContextInitialized = false;
  61958. this.canUseWebAudio = false;
  61959. this.WarnedWebAudioUnsupported = false;
  61960. this.unlocked = false;
  61961. this.isMP3supported = false;
  61962. this.isOGGsupported = false;
  61963. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61964. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61965. this.canUseWebAudio = true;
  61966. }
  61967. var audioElem = document.createElement('audio');
  61968. try {
  61969. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61970. this.isMP3supported = true;
  61971. }
  61972. }
  61973. catch (e) {
  61974. // protect error during capability check.
  61975. }
  61976. try {
  61977. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61978. this.isOGGsupported = true;
  61979. }
  61980. }
  61981. catch (e) {
  61982. // protect error during capability check.
  61983. }
  61984. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61985. this._unlockiOSaudio();
  61986. }
  61987. else {
  61988. this.unlocked = true;
  61989. }
  61990. }
  61991. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61992. get: function () {
  61993. if (!this._audioContextInitialized) {
  61994. this._initializeAudioContext();
  61995. }
  61996. return this._audioContext;
  61997. },
  61998. enumerable: true,
  61999. configurable: true
  62000. });
  62001. AudioEngine.prototype._unlockiOSaudio = function () {
  62002. var _this = this;
  62003. var unlockaudio = function () {
  62004. if (!_this.audioContext) {
  62005. return;
  62006. }
  62007. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62008. var source = _this.audioContext.createBufferSource();
  62009. source.buffer = buffer;
  62010. source.connect(_this.audioContext.destination);
  62011. source.start(0);
  62012. setTimeout(function () {
  62013. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62014. _this.unlocked = true;
  62015. window.removeEventListener('touchend', unlockaudio, false);
  62016. if (_this.onAudioUnlocked) {
  62017. _this.onAudioUnlocked();
  62018. }
  62019. }
  62020. }, 0);
  62021. };
  62022. window.addEventListener('touchend', unlockaudio, false);
  62023. };
  62024. AudioEngine.prototype._initializeAudioContext = function () {
  62025. try {
  62026. if (this.canUseWebAudio) {
  62027. this._audioContext = new AudioContext();
  62028. // create a global volume gain node
  62029. this.masterGain = this._audioContext.createGain();
  62030. this.masterGain.gain.value = 1;
  62031. this.masterGain.connect(this._audioContext.destination);
  62032. this._audioContextInitialized = true;
  62033. }
  62034. }
  62035. catch (e) {
  62036. this.canUseWebAudio = false;
  62037. BABYLON.Tools.Error("Web Audio: " + e.message);
  62038. }
  62039. };
  62040. AudioEngine.prototype.dispose = function () {
  62041. if (this.canUseWebAudio && this._audioContextInitialized) {
  62042. if (this._connectedAnalyser && this._audioContext) {
  62043. this._connectedAnalyser.stopDebugCanvas();
  62044. this._connectedAnalyser.dispose();
  62045. this.masterGain.disconnect();
  62046. this.masterGain.connect(this._audioContext.destination);
  62047. this._connectedAnalyser = null;
  62048. }
  62049. this.masterGain.gain.value = 1;
  62050. }
  62051. this.WarnedWebAudioUnsupported = false;
  62052. };
  62053. AudioEngine.prototype.getGlobalVolume = function () {
  62054. if (this.canUseWebAudio && this._audioContextInitialized) {
  62055. return this.masterGain.gain.value;
  62056. }
  62057. else {
  62058. return -1;
  62059. }
  62060. };
  62061. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62062. if (this.canUseWebAudio && this._audioContextInitialized) {
  62063. this.masterGain.gain.value = newVolume;
  62064. }
  62065. };
  62066. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62067. if (this._connectedAnalyser) {
  62068. this._connectedAnalyser.stopDebugCanvas();
  62069. }
  62070. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62071. this._connectedAnalyser = analyser;
  62072. this.masterGain.disconnect();
  62073. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62074. }
  62075. };
  62076. return AudioEngine;
  62077. }());
  62078. BABYLON.AudioEngine = AudioEngine;
  62079. })(BABYLON || (BABYLON = {}));
  62080. //# sourceMappingURL=babylon.audioEngine.js.map
  62081. var BABYLON;
  62082. (function (BABYLON) {
  62083. var Sound = /** @class */ (function () {
  62084. /**
  62085. * Create a sound and attach it to a scene
  62086. * @param name Name of your sound
  62087. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62088. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62089. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62090. */
  62091. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62092. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62093. var _this = this;
  62094. this.autoplay = false;
  62095. this.loop = false;
  62096. this.useCustomAttenuation = false;
  62097. this.spatialSound = false;
  62098. this.refDistance = 1;
  62099. this.rolloffFactor = 1;
  62100. this.maxDistance = 100;
  62101. this.distanceModel = "linear";
  62102. this._panningModel = "equalpower";
  62103. this._playbackRate = 1;
  62104. this._streaming = false;
  62105. this._startTime = 0;
  62106. this._startOffset = 0;
  62107. this._position = BABYLON.Vector3.Zero();
  62108. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62109. this._volume = 1;
  62110. this._isReadyToPlay = false;
  62111. this.isPlaying = false;
  62112. this.isPaused = false;
  62113. this._isDirectional = false;
  62114. // Used if you'd like to create a directional sound.
  62115. // If not set, the sound will be omnidirectional
  62116. this._coneInnerAngle = 360;
  62117. this._coneOuterAngle = 360;
  62118. this._coneOuterGain = 0;
  62119. this._isOutputConnected = false;
  62120. this._urlType = "Unknown";
  62121. this.name = name;
  62122. this._scene = scene;
  62123. this._readyToPlayCallback = readyToPlayCallback;
  62124. // Default custom attenuation function is a linear attenuation
  62125. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62126. if (currentDistance < maxDistance) {
  62127. return currentVolume * (1 - currentDistance / maxDistance);
  62128. }
  62129. else {
  62130. return 0;
  62131. }
  62132. };
  62133. if (options) {
  62134. this.autoplay = options.autoplay || false;
  62135. this.loop = options.loop || false;
  62136. // if volume === 0, we need another way to check this option
  62137. if (options.volume !== undefined) {
  62138. this._volume = options.volume;
  62139. }
  62140. this.spatialSound = options.spatialSound || false;
  62141. this.maxDistance = options.maxDistance || 100;
  62142. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62143. this.rolloffFactor = options.rolloffFactor || 1;
  62144. this.refDistance = options.refDistance || 1;
  62145. this.distanceModel = options.distanceModel || "linear";
  62146. this._playbackRate = options.playbackRate || 1;
  62147. this._streaming = options.streaming || false;
  62148. }
  62149. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62150. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62151. this._soundGain.gain.value = this._volume;
  62152. this._inputAudioNode = this._soundGain;
  62153. this._ouputAudioNode = this._soundGain;
  62154. if (this.spatialSound) {
  62155. this._createSpatialParameters();
  62156. }
  62157. this._scene.mainSoundTrack.AddSound(this);
  62158. var validParameter = true;
  62159. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62160. if (urlOrArrayBuffer) {
  62161. try {
  62162. if (typeof (urlOrArrayBuffer) === "string")
  62163. this._urlType = "String";
  62164. if (Array.isArray(urlOrArrayBuffer))
  62165. this._urlType = "Array";
  62166. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62167. this._urlType = "ArrayBuffer";
  62168. var urls = [];
  62169. var codecSupportedFound = false;
  62170. switch (this._urlType) {
  62171. case "ArrayBuffer":
  62172. if (urlOrArrayBuffer.byteLength > 0) {
  62173. codecSupportedFound = true;
  62174. this._soundLoaded(urlOrArrayBuffer);
  62175. }
  62176. break;
  62177. case "String":
  62178. urls.push(urlOrArrayBuffer);
  62179. case "Array":
  62180. if (urls.length === 0)
  62181. urls = urlOrArrayBuffer;
  62182. // If we found a supported format, we load it immediately and stop the loop
  62183. for (var i = 0; i < urls.length; i++) {
  62184. var url = urls[i];
  62185. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62186. codecSupportedFound = true;
  62187. }
  62188. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62189. codecSupportedFound = true;
  62190. }
  62191. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62192. codecSupportedFound = true;
  62193. }
  62194. if (url.indexOf("blob:") !== -1) {
  62195. codecSupportedFound = true;
  62196. }
  62197. if (codecSupportedFound) {
  62198. // Loading sound using XHR2
  62199. if (!this._streaming) {
  62200. this._scene._loadFile(url, function (data) {
  62201. _this._soundLoaded(data);
  62202. }, undefined, true, true, function (exception) {
  62203. if (exception) {
  62204. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62205. }
  62206. BABYLON.Tools.Error("Sound creation aborted.");
  62207. _this._scene.mainSoundTrack.RemoveSound(_this);
  62208. });
  62209. }
  62210. // Streaming sound using HTML5 Audio tag
  62211. else {
  62212. this._htmlAudioElement = new Audio(url);
  62213. this._htmlAudioElement.controls = false;
  62214. this._htmlAudioElement.loop = this.loop;
  62215. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62216. this._htmlAudioElement.preload = "auto";
  62217. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62218. _this._isReadyToPlay = true;
  62219. if (_this.autoplay) {
  62220. _this.play();
  62221. }
  62222. if (_this._readyToPlayCallback) {
  62223. _this._readyToPlayCallback();
  62224. }
  62225. });
  62226. document.body.appendChild(this._htmlAudioElement);
  62227. }
  62228. break;
  62229. }
  62230. }
  62231. break;
  62232. default:
  62233. validParameter = false;
  62234. break;
  62235. }
  62236. if (!validParameter) {
  62237. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62238. }
  62239. else {
  62240. if (!codecSupportedFound) {
  62241. this._isReadyToPlay = true;
  62242. // Simulating a ready to play event to avoid breaking code path
  62243. if (this._readyToPlayCallback) {
  62244. window.setTimeout(function () {
  62245. if (_this._readyToPlayCallback) {
  62246. _this._readyToPlayCallback();
  62247. }
  62248. }, 1000);
  62249. }
  62250. }
  62251. }
  62252. }
  62253. catch (ex) {
  62254. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62255. this._scene.mainSoundTrack.RemoveSound(this);
  62256. }
  62257. }
  62258. }
  62259. else {
  62260. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62261. this._scene.mainSoundTrack.AddSound(this);
  62262. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62263. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62264. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62265. }
  62266. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62267. if (this._readyToPlayCallback) {
  62268. window.setTimeout(function () {
  62269. if (_this._readyToPlayCallback) {
  62270. _this._readyToPlayCallback();
  62271. }
  62272. }, 1000);
  62273. }
  62274. }
  62275. }
  62276. Sound.prototype.dispose = function () {
  62277. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62278. if (this.isPlaying) {
  62279. this.stop();
  62280. }
  62281. this._isReadyToPlay = false;
  62282. if (this.soundTrackId === -1) {
  62283. this._scene.mainSoundTrack.RemoveSound(this);
  62284. }
  62285. else {
  62286. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62287. }
  62288. if (this._soundGain) {
  62289. this._soundGain.disconnect();
  62290. this._soundGain = null;
  62291. }
  62292. if (this._soundPanner) {
  62293. this._soundPanner.disconnect();
  62294. this._soundPanner = null;
  62295. }
  62296. if (this._soundSource) {
  62297. this._soundSource.disconnect();
  62298. this._soundSource = null;
  62299. }
  62300. this._audioBuffer = null;
  62301. if (this._htmlAudioElement) {
  62302. this._htmlAudioElement.pause();
  62303. this._htmlAudioElement.src = "";
  62304. document.body.removeChild(this._htmlAudioElement);
  62305. }
  62306. if (this._connectedMesh && this._registerFunc) {
  62307. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62308. this._connectedMesh = null;
  62309. }
  62310. }
  62311. };
  62312. Sound.prototype.isReady = function () {
  62313. return this._isReadyToPlay;
  62314. };
  62315. Sound.prototype._soundLoaded = function (audioData) {
  62316. var _this = this;
  62317. if (!BABYLON.Engine.audioEngine.audioContext) {
  62318. return;
  62319. }
  62320. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62321. _this._audioBuffer = buffer;
  62322. _this._isReadyToPlay = true;
  62323. if (_this.autoplay) {
  62324. _this.play();
  62325. }
  62326. if (_this._readyToPlayCallback) {
  62327. _this._readyToPlayCallback();
  62328. }
  62329. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62330. };
  62331. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62332. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62333. this._audioBuffer = audioBuffer;
  62334. this._isReadyToPlay = true;
  62335. }
  62336. };
  62337. Sound.prototype.updateOptions = function (options) {
  62338. if (options) {
  62339. this.loop = options.loop || this.loop;
  62340. this.maxDistance = options.maxDistance || this.maxDistance;
  62341. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62342. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62343. this.refDistance = options.refDistance || this.refDistance;
  62344. this.distanceModel = options.distanceModel || this.distanceModel;
  62345. this._playbackRate = options.playbackRate || this._playbackRate;
  62346. this._updateSpatialParameters();
  62347. if (this.isPlaying) {
  62348. if (this._streaming) {
  62349. this._htmlAudioElement.playbackRate = this._playbackRate;
  62350. }
  62351. else {
  62352. if (this._soundSource) {
  62353. this._soundSource.playbackRate.value = this._playbackRate;
  62354. }
  62355. }
  62356. }
  62357. }
  62358. };
  62359. Sound.prototype._createSpatialParameters = function () {
  62360. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62361. if (this._scene.headphone) {
  62362. this._panningModel = "HRTF";
  62363. }
  62364. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62365. this._updateSpatialParameters();
  62366. this._soundPanner.connect(this._ouputAudioNode);
  62367. this._inputAudioNode = this._soundPanner;
  62368. }
  62369. };
  62370. Sound.prototype._updateSpatialParameters = function () {
  62371. if (this.spatialSound && this._soundPanner) {
  62372. if (this.useCustomAttenuation) {
  62373. // Tricks to disable in a way embedded Web Audio attenuation
  62374. this._soundPanner.distanceModel = "linear";
  62375. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62376. this._soundPanner.refDistance = 1;
  62377. this._soundPanner.rolloffFactor = 1;
  62378. this._soundPanner.panningModel = this._panningModel;
  62379. }
  62380. else {
  62381. this._soundPanner.distanceModel = this.distanceModel;
  62382. this._soundPanner.maxDistance = this.maxDistance;
  62383. this._soundPanner.refDistance = this.refDistance;
  62384. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62385. this._soundPanner.panningModel = this._panningModel;
  62386. }
  62387. }
  62388. };
  62389. Sound.prototype.switchPanningModelToHRTF = function () {
  62390. this._panningModel = "HRTF";
  62391. this._switchPanningModel();
  62392. };
  62393. Sound.prototype.switchPanningModelToEqualPower = function () {
  62394. this._panningModel = "equalpower";
  62395. this._switchPanningModel();
  62396. };
  62397. Sound.prototype._switchPanningModel = function () {
  62398. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62399. this._soundPanner.panningModel = this._panningModel;
  62400. }
  62401. };
  62402. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62403. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62404. if (this._isOutputConnected) {
  62405. this._ouputAudioNode.disconnect();
  62406. }
  62407. this._ouputAudioNode.connect(soundTrackAudioNode);
  62408. this._isOutputConnected = true;
  62409. }
  62410. };
  62411. /**
  62412. * Transform this sound into a directional source
  62413. * @param coneInnerAngle Size of the inner cone in degree
  62414. * @param coneOuterAngle Size of the outer cone in degree
  62415. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62416. */
  62417. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62418. if (coneOuterAngle < coneInnerAngle) {
  62419. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62420. return;
  62421. }
  62422. this._coneInnerAngle = coneInnerAngle;
  62423. this._coneOuterAngle = coneOuterAngle;
  62424. this._coneOuterGain = coneOuterGain;
  62425. this._isDirectional = true;
  62426. if (this.isPlaying && this.loop) {
  62427. this.stop();
  62428. this.play();
  62429. }
  62430. };
  62431. Sound.prototype.setPosition = function (newPosition) {
  62432. this._position = newPosition;
  62433. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62434. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62435. }
  62436. };
  62437. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62438. this._localDirection = newLocalDirection;
  62439. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62440. this._updateDirection();
  62441. }
  62442. };
  62443. Sound.prototype._updateDirection = function () {
  62444. if (!this._connectedMesh || !this._soundPanner) {
  62445. return;
  62446. }
  62447. var mat = this._connectedMesh.getWorldMatrix();
  62448. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62449. direction.normalize();
  62450. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62451. };
  62452. Sound.prototype.updateDistanceFromListener = function () {
  62453. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62454. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62455. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62456. }
  62457. };
  62458. Sound.prototype.setAttenuationFunction = function (callback) {
  62459. this._customAttenuationFunction = callback;
  62460. };
  62461. /**
  62462. * Play the sound
  62463. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62464. * @param offset (optional) Start the sound setting it at a specific time
  62465. */
  62466. Sound.prototype.play = function (time, offset) {
  62467. var _this = this;
  62468. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62469. try {
  62470. if (this._startOffset < 0) {
  62471. time = -this._startOffset;
  62472. this._startOffset = 0;
  62473. }
  62474. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62475. if (!this._soundSource || !this._streamingSource) {
  62476. if (this.spatialSound && this._soundPanner) {
  62477. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62478. if (this._isDirectional) {
  62479. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62480. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62481. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62482. if (this._connectedMesh) {
  62483. this._updateDirection();
  62484. }
  62485. else {
  62486. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62487. }
  62488. }
  62489. }
  62490. }
  62491. if (this._streaming) {
  62492. if (!this._streamingSource) {
  62493. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62494. this._htmlAudioElement.onended = function () { _this._onended(); };
  62495. this._htmlAudioElement.playbackRate = this._playbackRate;
  62496. }
  62497. this._streamingSource.disconnect();
  62498. this._streamingSource.connect(this._inputAudioNode);
  62499. this._htmlAudioElement.play();
  62500. }
  62501. else {
  62502. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62503. this._soundSource.buffer = this._audioBuffer;
  62504. this._soundSource.connect(this._inputAudioNode);
  62505. this._soundSource.loop = this.loop;
  62506. this._soundSource.playbackRate.value = this._playbackRate;
  62507. this._soundSource.onended = function () { _this._onended(); };
  62508. if (this._soundSource.buffer) {
  62509. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62510. }
  62511. }
  62512. this._startTime = startTime;
  62513. this.isPlaying = true;
  62514. this.isPaused = false;
  62515. }
  62516. catch (ex) {
  62517. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62518. }
  62519. }
  62520. };
  62521. Sound.prototype._onended = function () {
  62522. this.isPlaying = false;
  62523. if (this.onended) {
  62524. this.onended();
  62525. }
  62526. };
  62527. /**
  62528. * Stop the sound
  62529. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62530. */
  62531. Sound.prototype.stop = function (time) {
  62532. if (this.isPlaying) {
  62533. if (this._streaming) {
  62534. this._htmlAudioElement.pause();
  62535. // Test needed for Firefox or it will generate an Invalid State Error
  62536. if (this._htmlAudioElement.currentTime > 0) {
  62537. this._htmlAudioElement.currentTime = 0;
  62538. }
  62539. }
  62540. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62541. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62542. this._soundSource.stop(stopTime);
  62543. this._soundSource.onended = function () { };
  62544. if (!this.isPaused) {
  62545. this._startOffset = 0;
  62546. }
  62547. }
  62548. this.isPlaying = false;
  62549. }
  62550. };
  62551. Sound.prototype.pause = function () {
  62552. if (this.isPlaying) {
  62553. this.isPaused = true;
  62554. if (this._streaming) {
  62555. this._htmlAudioElement.pause();
  62556. }
  62557. else if (BABYLON.Engine.audioEngine.audioContext) {
  62558. this.stop(0);
  62559. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62560. }
  62561. }
  62562. };
  62563. Sound.prototype.setVolume = function (newVolume, time) {
  62564. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62565. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62566. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62567. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62568. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62569. }
  62570. else {
  62571. this._soundGain.gain.value = newVolume;
  62572. }
  62573. }
  62574. this._volume = newVolume;
  62575. };
  62576. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62577. this._playbackRate = newPlaybackRate;
  62578. if (this.isPlaying) {
  62579. if (this._streaming) {
  62580. this._htmlAudioElement.playbackRate = this._playbackRate;
  62581. }
  62582. else if (this._soundSource) {
  62583. this._soundSource.playbackRate.value = this._playbackRate;
  62584. }
  62585. }
  62586. };
  62587. Sound.prototype.getVolume = function () {
  62588. return this._volume;
  62589. };
  62590. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62591. var _this = this;
  62592. if (this._connectedMesh && this._registerFunc) {
  62593. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62594. this._registerFunc = null;
  62595. }
  62596. this._connectedMesh = meshToConnectTo;
  62597. if (!this.spatialSound) {
  62598. this.spatialSound = true;
  62599. this._createSpatialParameters();
  62600. if (this.isPlaying && this.loop) {
  62601. this.stop();
  62602. this.play();
  62603. }
  62604. }
  62605. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62606. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62607. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62608. };
  62609. Sound.prototype.detachFromMesh = function () {
  62610. if (this._connectedMesh && this._registerFunc) {
  62611. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62612. this._registerFunc = null;
  62613. this._connectedMesh = null;
  62614. }
  62615. };
  62616. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62617. if (!node.getBoundingInfo) {
  62618. return;
  62619. }
  62620. var mesh = node;
  62621. var boundingInfo = mesh.getBoundingInfo();
  62622. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62623. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62624. this._updateDirection();
  62625. }
  62626. };
  62627. Sound.prototype.clone = function () {
  62628. var _this = this;
  62629. if (!this._streaming) {
  62630. var setBufferAndRun = function () {
  62631. if (_this._isReadyToPlay) {
  62632. clonedSound._audioBuffer = _this.getAudioBuffer();
  62633. clonedSound._isReadyToPlay = true;
  62634. if (clonedSound.autoplay) {
  62635. clonedSound.play();
  62636. }
  62637. }
  62638. else {
  62639. window.setTimeout(setBufferAndRun, 300);
  62640. }
  62641. };
  62642. var currentOptions = {
  62643. autoplay: this.autoplay, loop: this.loop,
  62644. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62645. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62646. refDistance: this.refDistance, distanceModel: this.distanceModel
  62647. };
  62648. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62649. if (this.useCustomAttenuation) {
  62650. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62651. }
  62652. clonedSound.setPosition(this._position);
  62653. clonedSound.setPlaybackRate(this._playbackRate);
  62654. setBufferAndRun();
  62655. return clonedSound;
  62656. }
  62657. // Can't clone a streaming sound
  62658. else {
  62659. return null;
  62660. }
  62661. };
  62662. Sound.prototype.getAudioBuffer = function () {
  62663. return this._audioBuffer;
  62664. };
  62665. Sound.prototype.serialize = function () {
  62666. var serializationObject = {
  62667. name: this.name,
  62668. url: this.name,
  62669. autoplay: this.autoplay,
  62670. loop: this.loop,
  62671. volume: this._volume,
  62672. spatialSound: this.spatialSound,
  62673. maxDistance: this.maxDistance,
  62674. rolloffFactor: this.rolloffFactor,
  62675. refDistance: this.refDistance,
  62676. distanceModel: this.distanceModel,
  62677. playbackRate: this._playbackRate,
  62678. panningModel: this._panningModel,
  62679. soundTrackId: this.soundTrackId
  62680. };
  62681. if (this.spatialSound) {
  62682. if (this._connectedMesh)
  62683. serializationObject.connectedMeshId = this._connectedMesh.id;
  62684. serializationObject.position = this._position.asArray();
  62685. serializationObject.refDistance = this.refDistance;
  62686. serializationObject.distanceModel = this.distanceModel;
  62687. serializationObject.isDirectional = this._isDirectional;
  62688. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62689. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62690. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62691. serializationObject.coneOuterGain = this._coneOuterGain;
  62692. }
  62693. return serializationObject;
  62694. };
  62695. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62696. var soundName = parsedSound.name;
  62697. var soundUrl;
  62698. if (parsedSound.url) {
  62699. soundUrl = rootUrl + parsedSound.url;
  62700. }
  62701. else {
  62702. soundUrl = rootUrl + soundName;
  62703. }
  62704. var options = {
  62705. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62706. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62707. rolloffFactor: parsedSound.rolloffFactor,
  62708. refDistance: parsedSound.refDistance,
  62709. distanceModel: parsedSound.distanceModel,
  62710. playbackRate: parsedSound.playbackRate
  62711. };
  62712. var newSound;
  62713. if (!sourceSound) {
  62714. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62715. scene._addPendingData(newSound);
  62716. }
  62717. else {
  62718. var setBufferAndRun = function () {
  62719. if (sourceSound._isReadyToPlay) {
  62720. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62721. newSound._isReadyToPlay = true;
  62722. if (newSound.autoplay) {
  62723. newSound.play();
  62724. }
  62725. }
  62726. else {
  62727. window.setTimeout(setBufferAndRun, 300);
  62728. }
  62729. };
  62730. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62731. setBufferAndRun();
  62732. }
  62733. if (parsedSound.position) {
  62734. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62735. newSound.setPosition(soundPosition);
  62736. }
  62737. if (parsedSound.isDirectional) {
  62738. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62739. if (parsedSound.localDirectionToMesh) {
  62740. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62741. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62742. }
  62743. }
  62744. if (parsedSound.connectedMeshId) {
  62745. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62746. if (connectedMesh) {
  62747. newSound.attachToMesh(connectedMesh);
  62748. }
  62749. }
  62750. return newSound;
  62751. };
  62752. return Sound;
  62753. }());
  62754. BABYLON.Sound = Sound;
  62755. })(BABYLON || (BABYLON = {}));
  62756. //# sourceMappingURL=babylon.sound.js.map
  62757. var BABYLON;
  62758. (function (BABYLON) {
  62759. var SoundTrack = /** @class */ (function () {
  62760. function SoundTrack(scene, options) {
  62761. this.id = -1;
  62762. this._isMainTrack = false;
  62763. this._isInitialized = false;
  62764. this._scene = scene;
  62765. this.soundCollection = new Array();
  62766. this._options = options;
  62767. if (!this._isMainTrack) {
  62768. this._scene.soundTracks.push(this);
  62769. this.id = this._scene.soundTracks.length - 1;
  62770. }
  62771. }
  62772. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62773. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62774. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62775. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62776. if (this._options) {
  62777. if (this._options.volume) {
  62778. this._outputAudioNode.gain.value = this._options.volume;
  62779. }
  62780. if (this._options.mainTrack) {
  62781. this._isMainTrack = this._options.mainTrack;
  62782. }
  62783. }
  62784. this._isInitialized = true;
  62785. }
  62786. };
  62787. SoundTrack.prototype.dispose = function () {
  62788. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62789. if (this._connectedAnalyser) {
  62790. this._connectedAnalyser.stopDebugCanvas();
  62791. }
  62792. while (this.soundCollection.length) {
  62793. this.soundCollection[0].dispose();
  62794. }
  62795. if (this._outputAudioNode) {
  62796. this._outputAudioNode.disconnect();
  62797. }
  62798. this._outputAudioNode = null;
  62799. }
  62800. };
  62801. SoundTrack.prototype.AddSound = function (sound) {
  62802. if (!this._isInitialized) {
  62803. this._initializeSoundTrackAudioGraph();
  62804. }
  62805. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62806. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62807. }
  62808. if (sound.soundTrackId) {
  62809. if (sound.soundTrackId === -1) {
  62810. this._scene.mainSoundTrack.RemoveSound(sound);
  62811. }
  62812. else {
  62813. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62814. }
  62815. }
  62816. this.soundCollection.push(sound);
  62817. sound.soundTrackId = this.id;
  62818. };
  62819. SoundTrack.prototype.RemoveSound = function (sound) {
  62820. var index = this.soundCollection.indexOf(sound);
  62821. if (index !== -1) {
  62822. this.soundCollection.splice(index, 1);
  62823. }
  62824. };
  62825. SoundTrack.prototype.setVolume = function (newVolume) {
  62826. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62827. this._outputAudioNode.gain.value = newVolume;
  62828. }
  62829. };
  62830. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62831. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62832. for (var i = 0; i < this.soundCollection.length; i++) {
  62833. this.soundCollection[i].switchPanningModelToHRTF();
  62834. }
  62835. }
  62836. };
  62837. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62838. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62839. for (var i = 0; i < this.soundCollection.length; i++) {
  62840. this.soundCollection[i].switchPanningModelToEqualPower();
  62841. }
  62842. }
  62843. };
  62844. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62845. if (this._connectedAnalyser) {
  62846. this._connectedAnalyser.stopDebugCanvas();
  62847. }
  62848. this._connectedAnalyser = analyser;
  62849. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62850. this._outputAudioNode.disconnect();
  62851. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62852. }
  62853. };
  62854. return SoundTrack;
  62855. }());
  62856. BABYLON.SoundTrack = SoundTrack;
  62857. })(BABYLON || (BABYLON = {}));
  62858. //# sourceMappingURL=babylon.soundtrack.js.map
  62859. var BABYLON;
  62860. (function (BABYLON) {
  62861. /**
  62862. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62863. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62864. */
  62865. var Analyser = /** @class */ (function () {
  62866. /**
  62867. * Creates a new analyser
  62868. * @param scene defines hosting scene
  62869. */
  62870. function Analyser(scene) {
  62871. /**
  62872. * Gets or sets the smoothing
  62873. * @ignorenaming
  62874. */
  62875. this.SMOOTHING = 0.75;
  62876. /**
  62877. * Gets or sets the FFT table size
  62878. * @ignorenaming
  62879. */
  62880. this.FFT_SIZE = 512;
  62881. /**
  62882. * Gets or sets the bar graph amplitude
  62883. * @ignorenaming
  62884. */
  62885. this.BARGRAPHAMPLITUDE = 256;
  62886. /**
  62887. * Gets or sets the position of the debug canvas
  62888. * @ignorenaming
  62889. */
  62890. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62891. /**
  62892. * Gets or sets the debug canvas size
  62893. * @ignorenaming
  62894. */
  62895. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62896. this._scene = scene;
  62897. this._audioEngine = BABYLON.Engine.audioEngine;
  62898. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62899. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62900. this._webAudioAnalyser.minDecibels = -140;
  62901. this._webAudioAnalyser.maxDecibels = 0;
  62902. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62903. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62904. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62905. }
  62906. }
  62907. /**
  62908. * Get the number of data values you will have to play with for the visualization
  62909. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62910. * @returns a number
  62911. */
  62912. Analyser.prototype.getFrequencyBinCount = function () {
  62913. if (this._audioEngine.canUseWebAudio) {
  62914. return this._webAudioAnalyser.frequencyBinCount;
  62915. }
  62916. else {
  62917. return 0;
  62918. }
  62919. };
  62920. /**
  62921. * Gets the current frequency data as a byte array
  62922. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62923. * @returns a Uint8Array
  62924. */
  62925. Analyser.prototype.getByteFrequencyData = function () {
  62926. if (this._audioEngine.canUseWebAudio) {
  62927. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62928. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62929. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62930. }
  62931. return this._byteFreqs;
  62932. };
  62933. /**
  62934. * Gets the current waveform as a byte array
  62935. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62936. * @returns a Uint8Array
  62937. */
  62938. Analyser.prototype.getByteTimeDomainData = function () {
  62939. if (this._audioEngine.canUseWebAudio) {
  62940. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62941. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62942. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62943. }
  62944. return this._byteTime;
  62945. };
  62946. /**
  62947. * Gets the current frequency data as a float array
  62948. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62949. * @returns a Float32Array
  62950. */
  62951. Analyser.prototype.getFloatFrequencyData = function () {
  62952. if (this._audioEngine.canUseWebAudio) {
  62953. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62954. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62955. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62956. }
  62957. return this._floatFreqs;
  62958. };
  62959. /**
  62960. * Renders the debug canvas
  62961. */
  62962. Analyser.prototype.drawDebugCanvas = function () {
  62963. var _this = this;
  62964. if (this._audioEngine.canUseWebAudio) {
  62965. if (!this._debugCanvas) {
  62966. this._debugCanvas = document.createElement("canvas");
  62967. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62968. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62969. this._debugCanvas.style.position = "absolute";
  62970. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62971. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62972. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62973. document.body.appendChild(this._debugCanvas);
  62974. this._registerFunc = function () {
  62975. _this.drawDebugCanvas();
  62976. };
  62977. this._scene.registerBeforeRender(this._registerFunc);
  62978. }
  62979. if (this._registerFunc && this._debugCanvasContext) {
  62980. var workingArray = this.getByteFrequencyData();
  62981. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62982. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62983. // Draw the frequency domain chart.
  62984. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62985. var value = workingArray[i];
  62986. var percent = value / this.BARGRAPHAMPLITUDE;
  62987. var height = this.DEBUGCANVASSIZE.height * percent;
  62988. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62989. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62990. var hue = i / this.getFrequencyBinCount() * 360;
  62991. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62992. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62993. }
  62994. }
  62995. }
  62996. };
  62997. /**
  62998. * Stops rendering the debug canvas and removes it
  62999. */
  63000. Analyser.prototype.stopDebugCanvas = function () {
  63001. if (this._debugCanvas) {
  63002. if (this._registerFunc) {
  63003. this._scene.unregisterBeforeRender(this._registerFunc);
  63004. this._registerFunc = null;
  63005. }
  63006. document.body.removeChild(this._debugCanvas);
  63007. this._debugCanvas = null;
  63008. this._debugCanvasContext = null;
  63009. }
  63010. };
  63011. /**
  63012. * Connects two audio nodes
  63013. * @param inputAudioNode defines first node to connect
  63014. * @param outputAudioNode defines second node to connect
  63015. */
  63016. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63017. if (this._audioEngine.canUseWebAudio) {
  63018. inputAudioNode.connect(this._webAudioAnalyser);
  63019. this._webAudioAnalyser.connect(outputAudioNode);
  63020. }
  63021. };
  63022. /**
  63023. * Releases all associated resources
  63024. */
  63025. Analyser.prototype.dispose = function () {
  63026. if (this._audioEngine.canUseWebAudio) {
  63027. this._webAudioAnalyser.disconnect();
  63028. }
  63029. };
  63030. return Analyser;
  63031. }());
  63032. BABYLON.Analyser = Analyser;
  63033. })(BABYLON || (BABYLON = {}));
  63034. //# sourceMappingURL=babylon.analyser.js.map
  63035. var BABYLON;
  63036. (function (BABYLON) {
  63037. var CubeTexture = /** @class */ (function (_super) {
  63038. __extends(CubeTexture, _super);
  63039. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  63040. if (extensions === void 0) { extensions = null; }
  63041. if (noMipmap === void 0) { noMipmap = false; }
  63042. if (files === void 0) { files = null; }
  63043. if (onLoad === void 0) { onLoad = null; }
  63044. if (onError === void 0) { onError = null; }
  63045. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63046. if (prefiltered === void 0) { prefiltered = false; }
  63047. if (forcedExtension === void 0) { forcedExtension = null; }
  63048. var _this = _super.call(this, scene) || this;
  63049. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63050. /**
  63051. * Gets or sets the center of the bounding box associated with the cube texture
  63052. * It must define where the camera used to render the texture was set
  63053. */
  63054. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63055. _this._rotationY = 0;
  63056. _this.name = rootUrl;
  63057. _this.url = rootUrl;
  63058. _this._noMipmap = noMipmap;
  63059. _this.hasAlpha = false;
  63060. _this._format = format;
  63061. _this._prefiltered = prefiltered;
  63062. _this.isCube = true;
  63063. _this._textureMatrix = BABYLON.Matrix.Identity();
  63064. if (prefiltered) {
  63065. _this.gammaSpace = false;
  63066. }
  63067. if (!rootUrl && !files) {
  63068. return _this;
  63069. }
  63070. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63071. var lastDot = rootUrl.lastIndexOf(".");
  63072. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63073. var isDDS = (extension === ".dds");
  63074. if (!files) {
  63075. if (!isDDS && !extensions) {
  63076. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63077. }
  63078. files = [];
  63079. if (extensions) {
  63080. for (var index = 0; index < extensions.length; index++) {
  63081. files.push(rootUrl + extensions[index]);
  63082. }
  63083. }
  63084. }
  63085. _this._files = files;
  63086. if (!_this._texture) {
  63087. if (!scene.useDelayedTextureLoading) {
  63088. if (prefiltered) {
  63089. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  63090. }
  63091. else {
  63092. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  63093. }
  63094. }
  63095. else {
  63096. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63097. }
  63098. }
  63099. else if (onLoad) {
  63100. if (_this._texture.isReady) {
  63101. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63102. }
  63103. else {
  63104. _this._texture.onLoadedObservable.add(onLoad);
  63105. }
  63106. }
  63107. return _this;
  63108. }
  63109. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63110. get: function () {
  63111. return this._boundingBoxSize;
  63112. },
  63113. /**
  63114. * Gets or sets the size of the bounding box associated with the cube texture
  63115. * When defined, the cubemap will switch to local mode
  63116. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63117. * @example https://www.babylonjs-playground.com/#RNASML
  63118. */
  63119. set: function (value) {
  63120. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63121. return;
  63122. }
  63123. this._boundingBoxSize = value;
  63124. var scene = this.getScene();
  63125. if (scene) {
  63126. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63127. }
  63128. },
  63129. enumerable: true,
  63130. configurable: true
  63131. });
  63132. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63133. /**
  63134. * Gets texture matrix rotation angle around Y axis radians.
  63135. */
  63136. get: function () {
  63137. return this._rotationY;
  63138. },
  63139. /**
  63140. * Sets texture matrix rotation angle around Y axis in radians.
  63141. */
  63142. set: function (value) {
  63143. this._rotationY = value;
  63144. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63145. },
  63146. enumerable: true,
  63147. configurable: true
  63148. });
  63149. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63150. var rootUrlKey = "";
  63151. files.forEach(function (url) { return rootUrlKey += url; });
  63152. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63153. };
  63154. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  63155. if (forcedExtension === void 0) { forcedExtension = null; }
  63156. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  63157. };
  63158. // Methods
  63159. CubeTexture.prototype.delayLoad = function () {
  63160. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63161. return;
  63162. }
  63163. var scene = this.getScene();
  63164. if (!scene) {
  63165. return;
  63166. }
  63167. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63168. this._texture = this._getFromCache(this.url, this._noMipmap);
  63169. if (!this._texture) {
  63170. if (this._prefiltered) {
  63171. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  63172. }
  63173. else {
  63174. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63175. }
  63176. }
  63177. };
  63178. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63179. return this._textureMatrix;
  63180. };
  63181. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63182. this._textureMatrix = value;
  63183. };
  63184. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63185. var texture = BABYLON.SerializationHelper.Parse(function () {
  63186. var prefiltered = false;
  63187. if (parsedTexture.prefiltered) {
  63188. prefiltered = parsedTexture.prefiltered;
  63189. }
  63190. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63191. }, parsedTexture, scene);
  63192. // Local Cubemaps
  63193. if (parsedTexture.boundingBoxPosition) {
  63194. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63195. }
  63196. if (parsedTexture.boundingBoxSize) {
  63197. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63198. }
  63199. // Animations
  63200. if (parsedTexture.animations) {
  63201. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63202. var parsedAnimation = parsedTexture.animations[animationIndex];
  63203. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63204. }
  63205. }
  63206. return texture;
  63207. };
  63208. CubeTexture.prototype.clone = function () {
  63209. var _this = this;
  63210. return BABYLON.SerializationHelper.Clone(function () {
  63211. var scene = _this.getScene();
  63212. if (!scene) {
  63213. return _this;
  63214. }
  63215. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63216. }, this);
  63217. };
  63218. __decorate([
  63219. BABYLON.serialize("rotationY")
  63220. ], CubeTexture.prototype, "_rotationY", void 0);
  63221. return CubeTexture;
  63222. }(BABYLON.BaseTexture));
  63223. BABYLON.CubeTexture = CubeTexture;
  63224. })(BABYLON || (BABYLON = {}));
  63225. //# sourceMappingURL=babylon.cubeTexture.js.map
  63226. var BABYLON;
  63227. (function (BABYLON) {
  63228. var RenderTargetTexture = /** @class */ (function (_super) {
  63229. __extends(RenderTargetTexture, _super);
  63230. /**
  63231. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63232. * or used a shadow, depth texture...
  63233. * @param name The friendly name of the texture
  63234. * @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)
  63235. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63236. * @param generateMipMaps True if mip maps need to be generated after render.
  63237. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63238. * @param type The type of the buffer in the RTT (int, half float, float...)
  63239. * @param isCube True if a cube texture needs to be created
  63240. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63241. * @param generateDepthBuffer True to generate a depth buffer
  63242. * @param generateStencilBuffer True to generate a stencil buffer
  63243. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63244. */
  63245. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63246. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63247. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63248. if (isCube === void 0) { isCube = false; }
  63249. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63250. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63251. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63252. if (isMulti === void 0) { isMulti = false; }
  63253. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63254. _this.isCube = isCube;
  63255. /**
  63256. * Use this list to define the list of mesh you want to render.
  63257. */
  63258. _this.renderList = new Array();
  63259. _this.renderParticles = true;
  63260. _this.renderSprites = false;
  63261. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63262. _this.ignoreCameraViewport = false;
  63263. // Events
  63264. /**
  63265. * An event triggered when the texture is unbind.
  63266. */
  63267. _this.onBeforeBindObservable = new BABYLON.Observable();
  63268. /**
  63269. * An event triggered when the texture is unbind.
  63270. */
  63271. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63272. /**
  63273. * An event triggered before rendering the texture
  63274. */
  63275. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63276. /**
  63277. * An event triggered after rendering the texture
  63278. */
  63279. _this.onAfterRenderObservable = new BABYLON.Observable();
  63280. /**
  63281. * An event triggered after the texture clear
  63282. */
  63283. _this.onClearObservable = new BABYLON.Observable();
  63284. _this._currentRefreshId = -1;
  63285. _this._refreshRate = 1;
  63286. _this._samples = 1;
  63287. /**
  63288. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63289. * It must define where the camera used to render the texture is set
  63290. */
  63291. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63292. scene = _this.getScene();
  63293. if (!scene) {
  63294. return _this;
  63295. }
  63296. _this._engine = scene.getEngine();
  63297. _this.name = name;
  63298. _this.isRenderTarget = true;
  63299. _this._initialSizeParameter = size;
  63300. _this._processSizeParameter(size);
  63301. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63302. });
  63303. _this._generateMipMaps = generateMipMaps ? true : false;
  63304. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63305. // Rendering groups
  63306. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63307. if (isMulti) {
  63308. return _this;
  63309. }
  63310. _this._renderTargetOptions = {
  63311. generateMipMaps: generateMipMaps,
  63312. type: type,
  63313. samplingMode: samplingMode,
  63314. generateDepthBuffer: generateDepthBuffer,
  63315. generateStencilBuffer: generateStencilBuffer
  63316. };
  63317. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63318. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63319. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63320. }
  63321. if (isCube) {
  63322. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63323. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63324. _this._textureMatrix = BABYLON.Matrix.Identity();
  63325. }
  63326. else {
  63327. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63328. }
  63329. return _this;
  63330. }
  63331. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63332. get: function () {
  63333. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63334. },
  63335. enumerable: true,
  63336. configurable: true
  63337. });
  63338. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63339. get: function () {
  63340. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63341. },
  63342. enumerable: true,
  63343. configurable: true
  63344. });
  63345. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63346. get: function () {
  63347. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63348. },
  63349. enumerable: true,
  63350. configurable: true
  63351. });
  63352. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63353. set: function (callback) {
  63354. if (this._onAfterUnbindObserver) {
  63355. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63356. }
  63357. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63358. },
  63359. enumerable: true,
  63360. configurable: true
  63361. });
  63362. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63363. set: function (callback) {
  63364. if (this._onBeforeRenderObserver) {
  63365. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63366. }
  63367. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63368. },
  63369. enumerable: true,
  63370. configurable: true
  63371. });
  63372. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63373. set: function (callback) {
  63374. if (this._onAfterRenderObserver) {
  63375. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63376. }
  63377. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63378. },
  63379. enumerable: true,
  63380. configurable: true
  63381. });
  63382. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63383. set: function (callback) {
  63384. if (this._onClearObserver) {
  63385. this.onClearObservable.remove(this._onClearObserver);
  63386. }
  63387. this._onClearObserver = this.onClearObservable.add(callback);
  63388. },
  63389. enumerable: true,
  63390. configurable: true
  63391. });
  63392. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63393. get: function () {
  63394. return this._renderTargetOptions;
  63395. },
  63396. enumerable: true,
  63397. configurable: true
  63398. });
  63399. RenderTargetTexture.prototype._onRatioRescale = function () {
  63400. if (this._sizeRatio) {
  63401. this.resize(this._initialSizeParameter);
  63402. }
  63403. };
  63404. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63405. get: function () {
  63406. return this._boundingBoxSize;
  63407. },
  63408. /**
  63409. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63410. * When defined, the cubemap will switch to local mode
  63411. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63412. * @example https://www.babylonjs-playground.com/#RNASML
  63413. */
  63414. set: function (value) {
  63415. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63416. return;
  63417. }
  63418. this._boundingBoxSize = value;
  63419. var scene = this.getScene();
  63420. if (scene) {
  63421. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63422. }
  63423. },
  63424. enumerable: true,
  63425. configurable: true
  63426. });
  63427. /**
  63428. * Creates a depth stencil texture.
  63429. * This is only available in WebGL 2 or with the depth texture extension available.
  63430. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63431. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63432. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63433. */
  63434. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63435. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63436. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63437. if (generateStencil === void 0) { generateStencil = false; }
  63438. if (!this.getScene()) {
  63439. return;
  63440. }
  63441. var engine = this.getScene().getEngine();
  63442. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63443. bilinearFiltering: bilinearFiltering,
  63444. comparisonFunction: comparisonFunction,
  63445. generateStencil: generateStencil,
  63446. isCube: this.isCube
  63447. });
  63448. engine.setFrameBufferDepthStencilTexture(this);
  63449. };
  63450. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63451. if (size.ratio) {
  63452. this._sizeRatio = size.ratio;
  63453. this._size = {
  63454. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63455. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63456. };
  63457. }
  63458. else {
  63459. this._size = size;
  63460. }
  63461. };
  63462. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63463. get: function () {
  63464. return this._samples;
  63465. },
  63466. set: function (value) {
  63467. if (this._samples === value) {
  63468. return;
  63469. }
  63470. var scene = this.getScene();
  63471. if (!scene) {
  63472. return;
  63473. }
  63474. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63475. },
  63476. enumerable: true,
  63477. configurable: true
  63478. });
  63479. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63480. this._currentRefreshId = -1;
  63481. };
  63482. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63483. get: function () {
  63484. return this._refreshRate;
  63485. },
  63486. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63487. set: function (value) {
  63488. this._refreshRate = value;
  63489. this.resetRefreshCounter();
  63490. },
  63491. enumerable: true,
  63492. configurable: true
  63493. });
  63494. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63495. if (!this._postProcessManager) {
  63496. var scene = this.getScene();
  63497. if (!scene) {
  63498. return;
  63499. }
  63500. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63501. this._postProcesses = new Array();
  63502. }
  63503. this._postProcesses.push(postProcess);
  63504. this._postProcesses[0].autoClear = false;
  63505. };
  63506. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63507. if (!this._postProcesses) {
  63508. return;
  63509. }
  63510. if (dispose) {
  63511. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63512. var postProcess = _a[_i];
  63513. postProcess.dispose();
  63514. }
  63515. }
  63516. this._postProcesses = [];
  63517. };
  63518. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63519. if (!this._postProcesses) {
  63520. return;
  63521. }
  63522. var index = this._postProcesses.indexOf(postProcess);
  63523. if (index === -1) {
  63524. return;
  63525. }
  63526. this._postProcesses.splice(index, 1);
  63527. if (this._postProcesses.length > 0) {
  63528. this._postProcesses[0].autoClear = false;
  63529. }
  63530. };
  63531. RenderTargetTexture.prototype._shouldRender = function () {
  63532. if (this._currentRefreshId === -1) { // At least render once
  63533. this._currentRefreshId = 1;
  63534. return true;
  63535. }
  63536. if (this.refreshRate === this._currentRefreshId) {
  63537. this._currentRefreshId = 1;
  63538. return true;
  63539. }
  63540. this._currentRefreshId++;
  63541. return false;
  63542. };
  63543. RenderTargetTexture.prototype.getRenderSize = function () {
  63544. if (this._size.width) {
  63545. return this._size.width;
  63546. }
  63547. return this._size;
  63548. };
  63549. RenderTargetTexture.prototype.getRenderWidth = function () {
  63550. if (this._size.width) {
  63551. return this._size.width;
  63552. }
  63553. return this._size;
  63554. };
  63555. RenderTargetTexture.prototype.getRenderHeight = function () {
  63556. if (this._size.width) {
  63557. return this._size.height;
  63558. }
  63559. return this._size;
  63560. };
  63561. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63562. get: function () {
  63563. return true;
  63564. },
  63565. enumerable: true,
  63566. configurable: true
  63567. });
  63568. RenderTargetTexture.prototype.scale = function (ratio) {
  63569. var newSize = this.getRenderSize() * ratio;
  63570. this.resize(newSize);
  63571. };
  63572. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63573. if (this.isCube) {
  63574. return this._textureMatrix;
  63575. }
  63576. return _super.prototype.getReflectionTextureMatrix.call(this);
  63577. };
  63578. RenderTargetTexture.prototype.resize = function (size) {
  63579. this.releaseInternalTexture();
  63580. var scene = this.getScene();
  63581. if (!scene) {
  63582. return;
  63583. }
  63584. this._processSizeParameter(size);
  63585. if (this.isCube) {
  63586. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63587. }
  63588. else {
  63589. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63590. }
  63591. };
  63592. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63593. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63594. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63595. var scene = this.getScene();
  63596. if (!scene) {
  63597. return;
  63598. }
  63599. var engine = scene.getEngine();
  63600. if (this.useCameraPostProcesses !== undefined) {
  63601. useCameraPostProcess = this.useCameraPostProcesses;
  63602. }
  63603. if (this._waitingRenderList) {
  63604. this.renderList = [];
  63605. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63606. var id = this._waitingRenderList[index];
  63607. var mesh_1 = scene.getMeshByID(id);
  63608. if (mesh_1) {
  63609. this.renderList.push(mesh_1);
  63610. }
  63611. }
  63612. delete this._waitingRenderList;
  63613. }
  63614. // Is predicate defined?
  63615. if (this.renderListPredicate) {
  63616. if (this.renderList) {
  63617. this.renderList.splice(0); // Clear previous renderList
  63618. }
  63619. else {
  63620. this.renderList = [];
  63621. }
  63622. var scene = this.getScene();
  63623. if (!scene) {
  63624. return;
  63625. }
  63626. var sceneMeshes = scene.meshes;
  63627. for (var index = 0; index < sceneMeshes.length; index++) {
  63628. var mesh = sceneMeshes[index];
  63629. if (this.renderListPredicate(mesh)) {
  63630. this.renderList.push(mesh);
  63631. }
  63632. }
  63633. }
  63634. this.onBeforeBindObservable.notifyObservers(this);
  63635. // Set custom projection.
  63636. // Needs to be before binding to prevent changing the aspect ratio.
  63637. var camera;
  63638. if (this.activeCamera) {
  63639. camera = this.activeCamera;
  63640. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63641. if (this.activeCamera !== scene.activeCamera) {
  63642. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63643. }
  63644. }
  63645. else {
  63646. camera = scene.activeCamera;
  63647. if (camera) {
  63648. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63649. }
  63650. }
  63651. // Prepare renderingManager
  63652. this._renderingManager.reset();
  63653. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63654. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63655. var sceneRenderId = scene.getRenderId();
  63656. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63657. var mesh = currentRenderList[meshIndex];
  63658. if (mesh) {
  63659. if (!mesh.isReady(this.refreshRate === 0)) {
  63660. this.resetRefreshCounter();
  63661. continue;
  63662. }
  63663. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63664. var isMasked = void 0;
  63665. if (!this.renderList && camera) {
  63666. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63667. }
  63668. else {
  63669. isMasked = false;
  63670. }
  63671. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63672. mesh._activate(sceneRenderId);
  63673. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63674. var subMesh = mesh.subMeshes[subIndex];
  63675. scene._activeIndices.addCount(subMesh.indexCount, false);
  63676. this._renderingManager.dispatch(subMesh, mesh);
  63677. }
  63678. }
  63679. }
  63680. }
  63681. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63682. var particleSystem = scene.particleSystems[particleIndex];
  63683. var emitter = particleSystem.emitter;
  63684. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63685. continue;
  63686. }
  63687. if (currentRenderList.indexOf(emitter) >= 0) {
  63688. this._renderingManager.dispatchParticles(particleSystem);
  63689. }
  63690. }
  63691. if (this.isCube) {
  63692. for (var face = 0; face < 6; face++) {
  63693. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63694. scene.incrementRenderId();
  63695. scene.resetCachedMaterial();
  63696. }
  63697. }
  63698. else {
  63699. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63700. }
  63701. this.onAfterUnbindObservable.notifyObservers(this);
  63702. if (scene.activeCamera) {
  63703. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63704. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63705. }
  63706. engine.setViewport(scene.activeCamera.viewport);
  63707. }
  63708. scene.resetCachedMaterial();
  63709. };
  63710. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63711. var minimum = 128;
  63712. var x = renderDimension * scale;
  63713. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63714. // Ensure we don't exceed the render dimension (while staying POT)
  63715. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63716. };
  63717. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63718. var _this = this;
  63719. if (!this._texture) {
  63720. return;
  63721. }
  63722. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63723. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63724. });
  63725. };
  63726. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63727. var scene = this.getScene();
  63728. if (!scene) {
  63729. return;
  63730. }
  63731. var engine = scene.getEngine();
  63732. if (!this._texture) {
  63733. return;
  63734. }
  63735. // Bind
  63736. if (this._postProcessManager) {
  63737. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63738. }
  63739. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63740. if (this._texture) {
  63741. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63742. }
  63743. }
  63744. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63745. // Clear
  63746. if (this.onClearObservable.hasObservers()) {
  63747. this.onClearObservable.notifyObservers(engine);
  63748. }
  63749. else {
  63750. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63751. }
  63752. if (!this._doNotChangeAspectRatio) {
  63753. scene.updateTransformMatrix(true);
  63754. }
  63755. // Render
  63756. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63757. if (this._postProcessManager) {
  63758. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63759. }
  63760. else if (useCameraPostProcess) {
  63761. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63762. }
  63763. if (!this._doNotChangeAspectRatio) {
  63764. scene.updateTransformMatrix(true);
  63765. }
  63766. // Dump ?
  63767. if (dumpForDebug) {
  63768. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63769. }
  63770. // Unbind
  63771. if (!this.isCube || faceIndex === 5) {
  63772. if (this.isCube) {
  63773. if (faceIndex === 5) {
  63774. engine.generateMipMapsForCubemap(this._texture);
  63775. }
  63776. }
  63777. this.unbindFrameBuffer(engine, faceIndex);
  63778. }
  63779. else {
  63780. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63781. }
  63782. };
  63783. /**
  63784. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63785. * This allowed control for front to back rendering or reversly depending of the special needs.
  63786. *
  63787. * @param renderingGroupId The rendering group id corresponding to its index
  63788. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63789. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63790. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63791. */
  63792. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63793. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63794. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63795. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63796. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63797. };
  63798. /**
  63799. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63800. *
  63801. * @param renderingGroupId The rendering group id corresponding to its index
  63802. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63803. */
  63804. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63805. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63806. };
  63807. RenderTargetTexture.prototype.clone = function () {
  63808. var textureSize = this.getSize();
  63809. 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);
  63810. // Base texture
  63811. newTexture.hasAlpha = this.hasAlpha;
  63812. newTexture.level = this.level;
  63813. // RenderTarget Texture
  63814. newTexture.coordinatesMode = this.coordinatesMode;
  63815. if (this.renderList) {
  63816. newTexture.renderList = this.renderList.slice(0);
  63817. }
  63818. return newTexture;
  63819. };
  63820. RenderTargetTexture.prototype.serialize = function () {
  63821. if (!this.name) {
  63822. return null;
  63823. }
  63824. var serializationObject = _super.prototype.serialize.call(this);
  63825. serializationObject.renderTargetSize = this.getRenderSize();
  63826. serializationObject.renderList = [];
  63827. if (this.renderList) {
  63828. for (var index = 0; index < this.renderList.length; index++) {
  63829. serializationObject.renderList.push(this.renderList[index].id);
  63830. }
  63831. }
  63832. return serializationObject;
  63833. };
  63834. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63835. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63836. var objBuffer = this.getInternalTexture();
  63837. var scene = this.getScene();
  63838. if (objBuffer && scene) {
  63839. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63840. }
  63841. };
  63842. RenderTargetTexture.prototype.dispose = function () {
  63843. if (this._postProcessManager) {
  63844. this._postProcessManager.dispose();
  63845. this._postProcessManager = null;
  63846. }
  63847. this.clearPostProcesses(true);
  63848. if (this._resizeObserver) {
  63849. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63850. this._resizeObserver = null;
  63851. }
  63852. this.renderList = null;
  63853. // Remove from custom render targets
  63854. var scene = this.getScene();
  63855. if (!scene) {
  63856. return;
  63857. }
  63858. var index = scene.customRenderTargets.indexOf(this);
  63859. if (index >= 0) {
  63860. scene.customRenderTargets.splice(index, 1);
  63861. }
  63862. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63863. var camera = _a[_i];
  63864. index = camera.customRenderTargets.indexOf(this);
  63865. if (index >= 0) {
  63866. camera.customRenderTargets.splice(index, 1);
  63867. }
  63868. }
  63869. _super.prototype.dispose.call(this);
  63870. };
  63871. RenderTargetTexture.prototype._rebuild = function () {
  63872. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63873. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63874. }
  63875. if (this._postProcessManager) {
  63876. this._postProcessManager._rebuild();
  63877. }
  63878. };
  63879. /**
  63880. * Clear the info related to rendering groups preventing retention point in material dispose.
  63881. */
  63882. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63883. if (this._renderingManager) {
  63884. this._renderingManager.freeRenderingGroups();
  63885. }
  63886. };
  63887. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63888. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63889. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63890. return RenderTargetTexture;
  63891. }(BABYLON.Texture));
  63892. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63893. })(BABYLON || (BABYLON = {}));
  63894. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63895. var BABYLON;
  63896. (function (BABYLON) {
  63897. ;
  63898. var MultiRenderTarget = /** @class */ (function (_super) {
  63899. __extends(MultiRenderTarget, _super);
  63900. function MultiRenderTarget(name, size, count, scene, options) {
  63901. var _this = this;
  63902. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63903. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63904. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63905. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63906. _this._engine = scene.getEngine();
  63907. if (!_this.isSupported) {
  63908. _this.dispose();
  63909. return;
  63910. }
  63911. var types = [];
  63912. var samplingModes = [];
  63913. for (var i = 0; i < count; i++) {
  63914. if (options && options.types && options.types[i] !== undefined) {
  63915. types.push(options.types[i]);
  63916. }
  63917. else {
  63918. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63919. }
  63920. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63921. samplingModes.push(options.samplingModes[i]);
  63922. }
  63923. else {
  63924. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63925. }
  63926. }
  63927. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63928. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63929. _this._size = size;
  63930. _this._multiRenderTargetOptions = {
  63931. samplingModes: samplingModes,
  63932. generateMipMaps: generateMipMaps,
  63933. generateDepthBuffer: generateDepthBuffer,
  63934. generateStencilBuffer: generateStencilBuffer,
  63935. generateDepthTexture: generateDepthTexture,
  63936. types: types,
  63937. textureCount: count
  63938. };
  63939. _this._createInternalTextures();
  63940. _this._createTextures();
  63941. return _this;
  63942. }
  63943. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63944. get: function () {
  63945. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63946. },
  63947. enumerable: true,
  63948. configurable: true
  63949. });
  63950. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63951. get: function () {
  63952. return this._textures;
  63953. },
  63954. enumerable: true,
  63955. configurable: true
  63956. });
  63957. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63958. get: function () {
  63959. return this._textures[this._textures.length - 1];
  63960. },
  63961. enumerable: true,
  63962. configurable: true
  63963. });
  63964. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63965. set: function (wrap) {
  63966. if (this._textures) {
  63967. for (var i = 0; i < this._textures.length; i++) {
  63968. this._textures[i].wrapU = wrap;
  63969. }
  63970. }
  63971. },
  63972. enumerable: true,
  63973. configurable: true
  63974. });
  63975. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63976. set: function (wrap) {
  63977. if (this._textures) {
  63978. for (var i = 0; i < this._textures.length; i++) {
  63979. this._textures[i].wrapV = wrap;
  63980. }
  63981. }
  63982. },
  63983. enumerable: true,
  63984. configurable: true
  63985. });
  63986. MultiRenderTarget.prototype._rebuild = function () {
  63987. this.releaseInternalTextures();
  63988. this._createInternalTextures();
  63989. for (var i = 0; i < this._internalTextures.length; i++) {
  63990. var texture = this._textures[i];
  63991. texture._texture = this._internalTextures[i];
  63992. }
  63993. // Keeps references to frame buffer and stencil/depth buffer
  63994. this._texture = this._internalTextures[0];
  63995. };
  63996. MultiRenderTarget.prototype._createInternalTextures = function () {
  63997. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63998. };
  63999. MultiRenderTarget.prototype._createTextures = function () {
  64000. this._textures = [];
  64001. for (var i = 0; i < this._internalTextures.length; i++) {
  64002. var texture = new BABYLON.Texture(null, this.getScene());
  64003. texture._texture = this._internalTextures[i];
  64004. this._textures.push(texture);
  64005. }
  64006. // Keeps references to frame buffer and stencil/depth buffer
  64007. this._texture = this._internalTextures[0];
  64008. };
  64009. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64010. get: function () {
  64011. return this._samples;
  64012. },
  64013. set: function (value) {
  64014. if (this._samples === value) {
  64015. return;
  64016. }
  64017. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64018. },
  64019. enumerable: true,
  64020. configurable: true
  64021. });
  64022. MultiRenderTarget.prototype.resize = function (size) {
  64023. this.releaseInternalTextures();
  64024. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64025. this._createInternalTextures();
  64026. };
  64027. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64028. var _this = this;
  64029. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64030. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64031. });
  64032. };
  64033. MultiRenderTarget.prototype.dispose = function () {
  64034. this.releaseInternalTextures();
  64035. _super.prototype.dispose.call(this);
  64036. };
  64037. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64038. if (!this._internalTextures) {
  64039. return;
  64040. }
  64041. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64042. if (this._internalTextures[i] !== undefined) {
  64043. this._internalTextures[i].dispose();
  64044. this._internalTextures.splice(i, 1);
  64045. }
  64046. }
  64047. };
  64048. return MultiRenderTarget;
  64049. }(BABYLON.RenderTargetTexture));
  64050. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64051. })(BABYLON || (BABYLON = {}));
  64052. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64053. var BABYLON;
  64054. (function (BABYLON) {
  64055. var MirrorTexture = /** @class */ (function (_super) {
  64056. __extends(MirrorTexture, _super);
  64057. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64058. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64059. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64060. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64061. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64062. _this.scene = scene;
  64063. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64064. _this._transformMatrix = BABYLON.Matrix.Zero();
  64065. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64066. _this._adaptiveBlurKernel = 0;
  64067. _this._blurKernelX = 0;
  64068. _this._blurKernelY = 0;
  64069. _this._blurRatio = 1.0;
  64070. _this.ignoreCameraViewport = true;
  64071. _this._updateGammaSpace();
  64072. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64073. _this._updateGammaSpace;
  64074. });
  64075. _this.onBeforeRenderObservable.add(function () {
  64076. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64077. _this._savedViewMatrix = scene.getViewMatrix();
  64078. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64079. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64080. scene.clipPlane = _this.mirrorPlane;
  64081. scene.getEngine().cullBackFaces = false;
  64082. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64083. });
  64084. _this.onAfterRenderObservable.add(function () {
  64085. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64086. scene.getEngine().cullBackFaces = true;
  64087. scene._mirroredCameraPosition = null;
  64088. delete scene.clipPlane;
  64089. });
  64090. return _this;
  64091. }
  64092. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64093. get: function () {
  64094. return this._blurRatio;
  64095. },
  64096. set: function (value) {
  64097. if (this._blurRatio === value) {
  64098. return;
  64099. }
  64100. this._blurRatio = value;
  64101. this._preparePostProcesses();
  64102. },
  64103. enumerable: true,
  64104. configurable: true
  64105. });
  64106. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64107. set: function (value) {
  64108. this._adaptiveBlurKernel = value;
  64109. this._autoComputeBlurKernel();
  64110. },
  64111. enumerable: true,
  64112. configurable: true
  64113. });
  64114. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64115. set: function (value) {
  64116. this.blurKernelX = value;
  64117. this.blurKernelY = value;
  64118. },
  64119. enumerable: true,
  64120. configurable: true
  64121. });
  64122. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64123. get: function () {
  64124. return this._blurKernelX;
  64125. },
  64126. set: function (value) {
  64127. if (this._blurKernelX === value) {
  64128. return;
  64129. }
  64130. this._blurKernelX = value;
  64131. this._preparePostProcesses();
  64132. },
  64133. enumerable: true,
  64134. configurable: true
  64135. });
  64136. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64137. get: function () {
  64138. return this._blurKernelY;
  64139. },
  64140. set: function (value) {
  64141. if (this._blurKernelY === value) {
  64142. return;
  64143. }
  64144. this._blurKernelY = value;
  64145. this._preparePostProcesses();
  64146. },
  64147. enumerable: true,
  64148. configurable: true
  64149. });
  64150. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64151. var engine = this.getScene().getEngine();
  64152. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64153. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64154. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64155. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64156. };
  64157. MirrorTexture.prototype._onRatioRescale = function () {
  64158. if (this._sizeRatio) {
  64159. this.resize(this._initialSizeParameter);
  64160. if (!this._adaptiveBlurKernel) {
  64161. this._preparePostProcesses();
  64162. }
  64163. }
  64164. if (this._adaptiveBlurKernel) {
  64165. this._autoComputeBlurKernel();
  64166. }
  64167. };
  64168. MirrorTexture.prototype._updateGammaSpace = function () {
  64169. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64170. };
  64171. MirrorTexture.prototype._preparePostProcesses = function () {
  64172. this.clearPostProcesses(true);
  64173. if (this._blurKernelX && this._blurKernelY) {
  64174. var engine = this.getScene().getEngine();
  64175. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64176. 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);
  64177. this._blurX.autoClear = false;
  64178. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64179. this._blurX.inputTexture = this._texture;
  64180. }
  64181. else {
  64182. this._blurX.alwaysForcePOT = true;
  64183. }
  64184. 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);
  64185. this._blurY.autoClear = false;
  64186. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64187. this.addPostProcess(this._blurX);
  64188. this.addPostProcess(this._blurY);
  64189. }
  64190. else {
  64191. if (this._blurY) {
  64192. this.removePostProcess(this._blurY);
  64193. this._blurY.dispose();
  64194. this._blurY = null;
  64195. }
  64196. if (this._blurX) {
  64197. this.removePostProcess(this._blurX);
  64198. this._blurX.dispose();
  64199. this._blurX = null;
  64200. }
  64201. }
  64202. };
  64203. MirrorTexture.prototype.clone = function () {
  64204. var scene = this.getScene();
  64205. if (!scene) {
  64206. return this;
  64207. }
  64208. var textureSize = this.getSize();
  64209. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64210. // Base texture
  64211. newTexture.hasAlpha = this.hasAlpha;
  64212. newTexture.level = this.level;
  64213. // Mirror Texture
  64214. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64215. if (this.renderList) {
  64216. newTexture.renderList = this.renderList.slice(0);
  64217. }
  64218. return newTexture;
  64219. };
  64220. MirrorTexture.prototype.serialize = function () {
  64221. if (!this.name) {
  64222. return null;
  64223. }
  64224. var serializationObject = _super.prototype.serialize.call(this);
  64225. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64226. return serializationObject;
  64227. };
  64228. MirrorTexture.prototype.dispose = function () {
  64229. _super.prototype.dispose.call(this);
  64230. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64231. };
  64232. return MirrorTexture;
  64233. }(BABYLON.RenderTargetTexture));
  64234. BABYLON.MirrorTexture = MirrorTexture;
  64235. })(BABYLON || (BABYLON = {}));
  64236. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64237. var BABYLON;
  64238. (function (BABYLON) {
  64239. /**
  64240. * Creates a refraction texture used by refraction channel of the standard material.
  64241. * @param name the texture name
  64242. * @param size size of the underlying texture
  64243. * @param scene root scene
  64244. */
  64245. var RefractionTexture = /** @class */ (function (_super) {
  64246. __extends(RefractionTexture, _super);
  64247. function RefractionTexture(name, size, scene, generateMipMaps) {
  64248. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64249. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64250. _this.depth = 2.0;
  64251. _this.onBeforeRenderObservable.add(function () {
  64252. scene.clipPlane = _this.refractionPlane;
  64253. });
  64254. _this.onAfterRenderObservable.add(function () {
  64255. delete scene.clipPlane;
  64256. });
  64257. return _this;
  64258. }
  64259. RefractionTexture.prototype.clone = function () {
  64260. var scene = this.getScene();
  64261. if (!scene) {
  64262. return this;
  64263. }
  64264. var textureSize = this.getSize();
  64265. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64266. // Base texture
  64267. newTexture.hasAlpha = this.hasAlpha;
  64268. newTexture.level = this.level;
  64269. // Refraction Texture
  64270. newTexture.refractionPlane = this.refractionPlane.clone();
  64271. if (this.renderList) {
  64272. newTexture.renderList = this.renderList.slice(0);
  64273. }
  64274. newTexture.depth = this.depth;
  64275. return newTexture;
  64276. };
  64277. RefractionTexture.prototype.serialize = function () {
  64278. if (!this.name) {
  64279. return null;
  64280. }
  64281. var serializationObject = _super.prototype.serialize.call(this);
  64282. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64283. serializationObject.depth = this.depth;
  64284. return serializationObject;
  64285. };
  64286. return RefractionTexture;
  64287. }(BABYLON.RenderTargetTexture));
  64288. BABYLON.RefractionTexture = RefractionTexture;
  64289. })(BABYLON || (BABYLON = {}));
  64290. //# sourceMappingURL=babylon.refractionTexture.js.map
  64291. var BABYLON;
  64292. (function (BABYLON) {
  64293. /**
  64294. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64295. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64296. */
  64297. var DynamicTexture = /** @class */ (function (_super) {
  64298. __extends(DynamicTexture, _super);
  64299. /**
  64300. * Creates a {BABYLON.DynamicTexture}
  64301. * @param name defines the name of the texture
  64302. * @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
  64303. * @param scene defines the scene where you want the texture
  64304. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64305. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64306. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64307. */
  64308. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64309. if (scene === void 0) { scene = null; }
  64310. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64311. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64312. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64313. _this.name = name;
  64314. _this._engine = _this.getScene().getEngine();
  64315. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64316. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64317. _this._generateMipMaps = generateMipMaps;
  64318. if (options.getContext) {
  64319. _this._canvas = options;
  64320. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64321. }
  64322. else {
  64323. _this._canvas = document.createElement("canvas");
  64324. if (options.width || options.width === 0) {
  64325. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64326. }
  64327. else {
  64328. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64329. }
  64330. }
  64331. var textureSize = _this.getSize();
  64332. _this._canvas.width = textureSize.width;
  64333. _this._canvas.height = textureSize.height;
  64334. _this._context = _this._canvas.getContext("2d");
  64335. return _this;
  64336. }
  64337. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64338. /**
  64339. * Gets the current state of canRescale
  64340. */
  64341. get: function () {
  64342. return true;
  64343. },
  64344. enumerable: true,
  64345. configurable: true
  64346. });
  64347. DynamicTexture.prototype._recreate = function (textureSize) {
  64348. this._canvas.width = textureSize.width;
  64349. this._canvas.height = textureSize.height;
  64350. this.releaseInternalTexture();
  64351. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64352. };
  64353. /**
  64354. * Scales the texture
  64355. * @param ratio the scale factor to apply to both width and height
  64356. */
  64357. DynamicTexture.prototype.scale = function (ratio) {
  64358. var textureSize = this.getSize();
  64359. textureSize.width *= ratio;
  64360. textureSize.height *= ratio;
  64361. this._recreate(textureSize);
  64362. };
  64363. /**
  64364. * Resizes the texture
  64365. * @param width the new width
  64366. * @param height the new height
  64367. */
  64368. DynamicTexture.prototype.scaleTo = function (width, height) {
  64369. var textureSize = this.getSize();
  64370. textureSize.width = width;
  64371. textureSize.height = height;
  64372. this._recreate(textureSize);
  64373. };
  64374. /**
  64375. * Gets the context of the canvas used by the texture
  64376. * @returns the canvas context of the dynamic texture
  64377. */
  64378. DynamicTexture.prototype.getContext = function () {
  64379. return this._context;
  64380. };
  64381. /**
  64382. * Clears the texture
  64383. */
  64384. DynamicTexture.prototype.clear = function () {
  64385. var size = this.getSize();
  64386. this._context.fillRect(0, 0, size.width, size.height);
  64387. };
  64388. /**
  64389. * Updates the texture
  64390. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64391. */
  64392. DynamicTexture.prototype.update = function (invertY) {
  64393. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  64394. };
  64395. /**
  64396. * Draws text onto the texture
  64397. * @param text defines the text to be drawn
  64398. * @param x defines the placement of the text from the left
  64399. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64400. * @param font defines the font to be used with font-style, font-size, font-name
  64401. * @param color defines the color used for the text
  64402. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64403. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64404. * @param update defines whether texture is immediately update (default is true)
  64405. */
  64406. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64407. if (update === void 0) { update = true; }
  64408. var size = this.getSize();
  64409. if (clearColor) {
  64410. this._context.fillStyle = clearColor;
  64411. this._context.fillRect(0, 0, size.width, size.height);
  64412. }
  64413. this._context.font = font;
  64414. if (x === null || x === undefined) {
  64415. var textSize = this._context.measureText(text);
  64416. x = (size.width - textSize.width) / 2;
  64417. }
  64418. if (y === null || y === undefined) {
  64419. var fontSize = parseInt((font.replace(/\D/g, '')));
  64420. y = (size.height / 2) + (fontSize / 3.65);
  64421. }
  64422. this._context.fillStyle = color;
  64423. this._context.fillText(text, x, y);
  64424. if (update) {
  64425. this.update(invertY);
  64426. }
  64427. };
  64428. /**
  64429. * Clones the texture
  64430. * @returns the clone of the texture.
  64431. */
  64432. DynamicTexture.prototype.clone = function () {
  64433. var scene = this.getScene();
  64434. if (!scene) {
  64435. return this;
  64436. }
  64437. var textureSize = this.getSize();
  64438. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64439. // Base texture
  64440. newTexture.hasAlpha = this.hasAlpha;
  64441. newTexture.level = this.level;
  64442. // Dynamic Texture
  64443. newTexture.wrapU = this.wrapU;
  64444. newTexture.wrapV = this.wrapV;
  64445. return newTexture;
  64446. };
  64447. /** @hidden */
  64448. DynamicTexture.prototype._rebuild = function () {
  64449. this.update();
  64450. };
  64451. return DynamicTexture;
  64452. }(BABYLON.Texture));
  64453. BABYLON.DynamicTexture = DynamicTexture;
  64454. })(BABYLON || (BABYLON = {}));
  64455. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64456. var BABYLON;
  64457. (function (BABYLON) {
  64458. var VideoTexture = /** @class */ (function (_super) {
  64459. __extends(VideoTexture, _super);
  64460. /**
  64461. * Creates a video texture.
  64462. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64463. * @param {string | null} name optional name, will detect from video source, if not defined
  64464. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64465. * @param {BABYLON.Scene} scene is obviously the current scene.
  64466. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64467. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64468. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64469. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64470. */
  64471. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64472. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64473. if (invertY === void 0) { invertY = false; }
  64474. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64475. if (settings === void 0) { settings = {
  64476. autoPlay: true,
  64477. loop: true,
  64478. autoUpdateTexture: true,
  64479. }; }
  64480. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64481. _this._stillImageCaptured = false;
  64482. _this._createInternalTexture = function () {
  64483. if (_this._texture != null) {
  64484. return;
  64485. }
  64486. if (!_this._engine.needPOTTextures ||
  64487. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64488. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64489. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64490. }
  64491. else {
  64492. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64493. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64494. _this._generateMipMaps = false;
  64495. }
  64496. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64497. if (!_this.video.autoplay) {
  64498. var oldHandler_1 = _this.video.onplaying;
  64499. _this.video.onplaying = function () {
  64500. _this.video.onplaying = oldHandler_1;
  64501. _this._texture.isReady = true;
  64502. _this._updateInternalTexture();
  64503. _this.video.pause();
  64504. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64505. _this.onLoadObservable.notifyObservers(_this);
  64506. }
  64507. };
  64508. _this.video.play();
  64509. }
  64510. else {
  64511. _this._texture.isReady = true;
  64512. _this._updateInternalTexture();
  64513. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64514. _this.onLoadObservable.notifyObservers(_this);
  64515. }
  64516. }
  64517. };
  64518. _this.reset = function () {
  64519. if (_this._texture == null) {
  64520. return;
  64521. }
  64522. _this._texture.dispose();
  64523. _this._texture = null;
  64524. };
  64525. _this._updateInternalTexture = function (e) {
  64526. if (_this._texture == null || !_this._texture.isReady) {
  64527. return;
  64528. }
  64529. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64530. return;
  64531. }
  64532. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64533. };
  64534. _this._engine = _this.getScene().getEngine();
  64535. _this._generateMipMaps = generateMipMaps;
  64536. _this._samplingMode = samplingMode;
  64537. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64538. _this.name = name || _this._getName(src);
  64539. _this.video = _this._getVideo(src);
  64540. if (settings.autoPlay !== undefined) {
  64541. _this.video.autoplay = settings.autoPlay;
  64542. }
  64543. if (settings.loop !== undefined) {
  64544. _this.video.loop = settings.loop;
  64545. }
  64546. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64547. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64548. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64549. _this.video.addEventListener("emptied", _this.reset);
  64550. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64551. _this._createInternalTexture();
  64552. }
  64553. return _this;
  64554. }
  64555. VideoTexture.prototype._getName = function (src) {
  64556. if (src instanceof HTMLVideoElement) {
  64557. return src.currentSrc;
  64558. }
  64559. if (typeof src === "object") {
  64560. return src.toString();
  64561. }
  64562. return src;
  64563. };
  64564. ;
  64565. VideoTexture.prototype._getVideo = function (src) {
  64566. if (src instanceof HTMLVideoElement) {
  64567. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64568. return src;
  64569. }
  64570. var video = document.createElement("video");
  64571. if (typeof src === "string") {
  64572. BABYLON.Tools.SetCorsBehavior(src, video);
  64573. video.src = src;
  64574. }
  64575. else {
  64576. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64577. src.forEach(function (url) {
  64578. var source = document.createElement("source");
  64579. source.src = url;
  64580. video.appendChild(source);
  64581. });
  64582. }
  64583. return video;
  64584. };
  64585. ;
  64586. /**
  64587. * Internal method to initiate `update`.
  64588. */
  64589. VideoTexture.prototype._rebuild = function () {
  64590. this.update();
  64591. };
  64592. /**
  64593. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64594. */
  64595. VideoTexture.prototype.update = function () {
  64596. if (!this.autoUpdateTexture) {
  64597. // Expecting user to call `updateTexture` manually
  64598. return;
  64599. }
  64600. this.updateTexture(true);
  64601. };
  64602. /**
  64603. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64604. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64605. */
  64606. VideoTexture.prototype.updateTexture = function (isVisible) {
  64607. if (!isVisible) {
  64608. return;
  64609. }
  64610. if (this.video.paused && this._stillImageCaptured) {
  64611. return;
  64612. }
  64613. this._stillImageCaptured = true;
  64614. this._updateInternalTexture();
  64615. };
  64616. /**
  64617. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64618. * @param url New url.
  64619. */
  64620. VideoTexture.prototype.updateURL = function (url) {
  64621. this.video.src = url;
  64622. };
  64623. VideoTexture.prototype.dispose = function () {
  64624. _super.prototype.dispose.call(this);
  64625. this.video.removeEventListener("canplay", this._createInternalTexture);
  64626. this.video.removeEventListener("paused", this._updateInternalTexture);
  64627. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64628. this.video.removeEventListener("emptied", this.reset);
  64629. this.video.pause();
  64630. };
  64631. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64632. var video = document.createElement("video");
  64633. var constraintsDeviceId;
  64634. if (constraints && constraints.deviceId) {
  64635. constraintsDeviceId = {
  64636. exact: constraints.deviceId,
  64637. };
  64638. }
  64639. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64640. if (navigator.mediaDevices) {
  64641. navigator.mediaDevices.getUserMedia({ video: constraints })
  64642. .then(function (stream) {
  64643. if (video.mozSrcObject !== undefined) {
  64644. // hack for Firefox < 19
  64645. video.mozSrcObject = stream;
  64646. }
  64647. else {
  64648. video.srcObject = stream;
  64649. }
  64650. var onPlaying = function () {
  64651. if (onReady) {
  64652. onReady(new VideoTexture("video", video, scene, true, true));
  64653. }
  64654. video.removeEventListener("playing", onPlaying);
  64655. };
  64656. video.addEventListener("playing", onPlaying);
  64657. video.play();
  64658. })
  64659. .catch(function (err) {
  64660. BABYLON.Tools.Error(err.name);
  64661. });
  64662. }
  64663. else {
  64664. navigator.getUserMedia =
  64665. navigator.getUserMedia ||
  64666. navigator.webkitGetUserMedia ||
  64667. navigator.mozGetUserMedia ||
  64668. navigator.msGetUserMedia;
  64669. if (navigator.getUserMedia) {
  64670. navigator.getUserMedia({
  64671. video: {
  64672. deviceId: constraintsDeviceId,
  64673. width: {
  64674. min: (constraints && constraints.minWidth) || 256,
  64675. max: (constraints && constraints.maxWidth) || 640,
  64676. },
  64677. height: {
  64678. min: (constraints && constraints.minHeight) || 256,
  64679. max: (constraints && constraints.maxHeight) || 480,
  64680. },
  64681. },
  64682. }, function (stream) {
  64683. if (video.mozSrcObject !== undefined) {
  64684. // hack for Firefox < 19
  64685. video.mozSrcObject = stream;
  64686. }
  64687. else {
  64688. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64689. }
  64690. video.play();
  64691. if (onReady) {
  64692. onReady(new VideoTexture("video", video, scene, true, true));
  64693. }
  64694. }, function (e) {
  64695. BABYLON.Tools.Error(e.name);
  64696. });
  64697. }
  64698. }
  64699. };
  64700. return VideoTexture;
  64701. }(BABYLON.Texture));
  64702. BABYLON.VideoTexture = VideoTexture;
  64703. })(BABYLON || (BABYLON = {}));
  64704. //# sourceMappingURL=babylon.videoTexture.js.map
  64705. var BABYLON;
  64706. (function (BABYLON) {
  64707. var RawTexture = /** @class */ (function (_super) {
  64708. __extends(RawTexture, _super);
  64709. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64710. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64711. if (invertY === void 0) { invertY = false; }
  64712. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64713. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64714. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64715. _this.format = format;
  64716. _this._engine = scene.getEngine();
  64717. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64718. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64719. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64720. return _this;
  64721. }
  64722. RawTexture.prototype.update = function (data) {
  64723. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64724. };
  64725. // Statics
  64726. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64727. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64728. if (invertY === void 0) { invertY = false; }
  64729. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64730. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64731. };
  64732. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64733. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64734. if (invertY === void 0) { invertY = false; }
  64735. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64736. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64737. };
  64738. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64739. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64740. if (invertY === void 0) { invertY = false; }
  64741. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64742. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64743. };
  64744. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64745. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64746. if (invertY === void 0) { invertY = false; }
  64747. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64748. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64749. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64750. };
  64751. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64752. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64753. if (invertY === void 0) { invertY = false; }
  64754. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64755. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64756. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64757. };
  64758. return RawTexture;
  64759. }(BABYLON.Texture));
  64760. BABYLON.RawTexture = RawTexture;
  64761. })(BABYLON || (BABYLON = {}));
  64762. //# sourceMappingURL=babylon.rawTexture.js.map
  64763. var BABYLON;
  64764. (function (BABYLON) {
  64765. /**
  64766. * Class used to store 3D textures containing user data
  64767. */
  64768. var RawTexture3D = /** @class */ (function (_super) {
  64769. __extends(RawTexture3D, _super);
  64770. /**
  64771. * Create a new RawTexture3D
  64772. * @param data defines the data of the texture
  64773. * @param width defines the width of the texture
  64774. * @param height defines the height of the texture
  64775. * @param depth defines the depth of the texture
  64776. * @param format defines the texture format to use
  64777. * @param scene defines the hosting scene
  64778. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64779. * @param invertY defines if texture must be stored with Y axis inverted
  64780. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64781. */
  64782. function RawTexture3D(data, width, height, depth,
  64783. /** Gets or sets the texture format to use*/
  64784. format, scene, generateMipMaps, invertY, samplingMode) {
  64785. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64786. if (invertY === void 0) { invertY = false; }
  64787. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64788. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64789. _this.format = format;
  64790. _this._engine = scene.getEngine();
  64791. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64792. _this.is3D = true;
  64793. return _this;
  64794. }
  64795. /**
  64796. * Update the texture with new data
  64797. * @param data defines the data to store in the texture
  64798. */
  64799. RawTexture3D.prototype.update = function (data) {
  64800. if (!this._texture) {
  64801. return;
  64802. }
  64803. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64804. };
  64805. return RawTexture3D;
  64806. }(BABYLON.Texture));
  64807. BABYLON.RawTexture3D = RawTexture3D;
  64808. })(BABYLON || (BABYLON = {}));
  64809. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64810. var BABYLON;
  64811. (function (BABYLON) {
  64812. /**
  64813. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64814. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64815. */
  64816. var PostProcess = /** @class */ (function () {
  64817. /**
  64818. * Creates a new instance PostProcess
  64819. * @param name The name of the PostProcess.
  64820. * @param fragmentUrl The url of the fragment shader to be used.
  64821. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64822. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64823. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64824. * @param camera The camera to apply the render pass to.
  64825. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64826. * @param engine The engine which the post process will be applied. (default: current engine)
  64827. * @param reusable If the post process can be reused on the same frame. (default: false)
  64828. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64829. * @param textureType Type of textures used when performing the post process. (default: 0)
  64830. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64831. * @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
  64832. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64833. */
  64834. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64835. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64836. if (defines === void 0) { defines = null; }
  64837. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64838. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64839. if (blockCompilation === void 0) { blockCompilation = false; }
  64840. this.name = name;
  64841. /**
  64842. * Width of the texture to apply the post process on
  64843. */
  64844. this.width = -1;
  64845. /**
  64846. * Height of the texture to apply the post process on
  64847. */
  64848. this.height = -1;
  64849. /**
  64850. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64851. */
  64852. this._outputTexture = null;
  64853. /**
  64854. * If the buffer needs to be cleared before applying the post process. (default: true)
  64855. * Should be set to false if shader will overwrite all previous pixels.
  64856. */
  64857. this.autoClear = true;
  64858. /**
  64859. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64860. */
  64861. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64862. /**
  64863. * Animations to be used for the post processing
  64864. */
  64865. this.animations = new Array();
  64866. /**
  64867. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64868. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64869. */
  64870. this.enablePixelPerfectMode = false;
  64871. /**
  64872. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64873. */
  64874. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64875. /**
  64876. * Force textures to be a power of two (default: false)
  64877. */
  64878. this.alwaysForcePOT = false;
  64879. /**
  64880. * Number of sample textures (default: 1)
  64881. */
  64882. this.samples = 1;
  64883. /**
  64884. * Modify the scale of the post process to be the same as the viewport (default: false)
  64885. */
  64886. this.adaptScaleToCurrentViewport = false;
  64887. this._reusable = false;
  64888. /**
  64889. * Smart array of input and output textures for the post process.
  64890. */
  64891. this._textures = new BABYLON.SmartArray(2);
  64892. /**
  64893. * The index in _textures that corresponds to the output texture.
  64894. */
  64895. this._currentRenderTextureInd = 0;
  64896. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64897. this._texelSize = BABYLON.Vector2.Zero();
  64898. // Events
  64899. /**
  64900. * An event triggered when the postprocess is activated.
  64901. */
  64902. this.onActivateObservable = new BABYLON.Observable();
  64903. /**
  64904. * An event triggered when the postprocess changes its size.
  64905. */
  64906. this.onSizeChangedObservable = new BABYLON.Observable();
  64907. /**
  64908. * An event triggered when the postprocess applies its effect.
  64909. */
  64910. this.onApplyObservable = new BABYLON.Observable();
  64911. /**
  64912. * An event triggered before rendering the postprocess
  64913. */
  64914. this.onBeforeRenderObservable = new BABYLON.Observable();
  64915. /**
  64916. * An event triggered after rendering the postprocess
  64917. */
  64918. this.onAfterRenderObservable = new BABYLON.Observable();
  64919. if (camera != null) {
  64920. this._camera = camera;
  64921. this._scene = camera.getScene();
  64922. camera.attachPostProcess(this);
  64923. this._engine = this._scene.getEngine();
  64924. this._scene.postProcesses.push(this);
  64925. }
  64926. else if (engine) {
  64927. this._engine = engine;
  64928. this._engine.postProcesses.push(this);
  64929. }
  64930. this._options = options;
  64931. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64932. this._reusable = reusable || false;
  64933. this._textureType = textureType;
  64934. this._samplers = samplers || [];
  64935. this._samplers.push("textureSampler");
  64936. this._fragmentUrl = fragmentUrl;
  64937. this._vertexUrl = vertexUrl;
  64938. this._parameters = parameters || [];
  64939. this._parameters.push("scale");
  64940. this._indexParameters = indexParameters;
  64941. if (!blockCompilation) {
  64942. this.updateEffect(defines);
  64943. }
  64944. }
  64945. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64946. /**
  64947. * A function that is added to the onActivateObservable
  64948. */
  64949. set: function (callback) {
  64950. if (this._onActivateObserver) {
  64951. this.onActivateObservable.remove(this._onActivateObserver);
  64952. }
  64953. if (callback) {
  64954. this._onActivateObserver = this.onActivateObservable.add(callback);
  64955. }
  64956. },
  64957. enumerable: true,
  64958. configurable: true
  64959. });
  64960. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64961. /**
  64962. * A function that is added to the onSizeChangedObservable
  64963. */
  64964. set: function (callback) {
  64965. if (this._onSizeChangedObserver) {
  64966. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64967. }
  64968. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64969. },
  64970. enumerable: true,
  64971. configurable: true
  64972. });
  64973. Object.defineProperty(PostProcess.prototype, "onApply", {
  64974. /**
  64975. * A function that is added to the onApplyObservable
  64976. */
  64977. set: function (callback) {
  64978. if (this._onApplyObserver) {
  64979. this.onApplyObservable.remove(this._onApplyObserver);
  64980. }
  64981. this._onApplyObserver = this.onApplyObservable.add(callback);
  64982. },
  64983. enumerable: true,
  64984. configurable: true
  64985. });
  64986. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64987. /**
  64988. * A function that is added to the onBeforeRenderObservable
  64989. */
  64990. set: function (callback) {
  64991. if (this._onBeforeRenderObserver) {
  64992. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64993. }
  64994. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64995. },
  64996. enumerable: true,
  64997. configurable: true
  64998. });
  64999. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65000. /**
  65001. * A function that is added to the onAfterRenderObservable
  65002. */
  65003. set: function (callback) {
  65004. if (this._onAfterRenderObserver) {
  65005. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65006. }
  65007. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65008. },
  65009. enumerable: true,
  65010. configurable: true
  65011. });
  65012. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65013. /**
  65014. * 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
  65015. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65016. */
  65017. get: function () {
  65018. return this._textures.data[this._currentRenderTextureInd];
  65019. },
  65020. set: function (value) {
  65021. this._forcedOutputTexture = value;
  65022. },
  65023. enumerable: true,
  65024. configurable: true
  65025. });
  65026. /**
  65027. * Gets the camera which post process is applied to.
  65028. * @returns The camera the post process is applied to.
  65029. */
  65030. PostProcess.prototype.getCamera = function () {
  65031. return this._camera;
  65032. };
  65033. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65034. /**
  65035. * Gets the texel size of the postprocess.
  65036. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65037. */
  65038. get: function () {
  65039. if (this._shareOutputWithPostProcess) {
  65040. return this._shareOutputWithPostProcess.texelSize;
  65041. }
  65042. if (this._forcedOutputTexture) {
  65043. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65044. }
  65045. return this._texelSize;
  65046. },
  65047. enumerable: true,
  65048. configurable: true
  65049. });
  65050. /**
  65051. * Gets the engine which this post process belongs to.
  65052. * @returns The engine the post process was enabled with.
  65053. */
  65054. PostProcess.prototype.getEngine = function () {
  65055. return this._engine;
  65056. };
  65057. /**
  65058. * The effect that is created when initializing the post process.
  65059. * @returns The created effect corrisponding the the postprocess.
  65060. */
  65061. PostProcess.prototype.getEffect = function () {
  65062. return this._effect;
  65063. };
  65064. /**
  65065. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65066. * @param postProcess The post process to share the output with.
  65067. * @returns This post process.
  65068. */
  65069. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65070. this._disposeTextures();
  65071. this._shareOutputWithPostProcess = postProcess;
  65072. return this;
  65073. };
  65074. /**
  65075. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65076. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65077. */
  65078. PostProcess.prototype.useOwnOutput = function () {
  65079. if (this._textures.length == 0) {
  65080. this._textures = new BABYLON.SmartArray(2);
  65081. }
  65082. this._shareOutputWithPostProcess = null;
  65083. };
  65084. /**
  65085. * Updates the effect with the current post process compile time values and recompiles the shader.
  65086. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65087. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65088. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65089. * @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
  65090. * @param onCompiled Called when the shader has been compiled.
  65091. * @param onError Called if there is an error when compiling a shader.
  65092. */
  65093. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65094. if (defines === void 0) { defines = null; }
  65095. if (uniforms === void 0) { uniforms = null; }
  65096. if (samplers === void 0) { samplers = null; }
  65097. 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);
  65098. };
  65099. /**
  65100. * The post process is reusable if it can be used multiple times within one frame.
  65101. * @returns If the post process is reusable
  65102. */
  65103. PostProcess.prototype.isReusable = function () {
  65104. return this._reusable;
  65105. };
  65106. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65107. PostProcess.prototype.markTextureDirty = function () {
  65108. this.width = -1;
  65109. };
  65110. /**
  65111. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65112. * 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.
  65113. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65114. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65115. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65116. * @returns The target texture that was bound to be written to.
  65117. */
  65118. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65119. var _this = this;
  65120. if (sourceTexture === void 0) { sourceTexture = null; }
  65121. camera = camera || this._camera;
  65122. var scene = camera.getScene();
  65123. var engine = scene.getEngine();
  65124. var maxSize = engine.getCaps().maxTextureSize;
  65125. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65126. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65127. // 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
  65128. var webVRCamera = camera.parent;
  65129. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65130. requiredWidth /= 2;
  65131. }
  65132. var desiredWidth = (this._options.width || requiredWidth);
  65133. var desiredHeight = this._options.height || requiredHeight;
  65134. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65135. if (this.adaptScaleToCurrentViewport) {
  65136. var currentViewport = engine.currentViewport;
  65137. if (currentViewport) {
  65138. desiredWidth *= currentViewport.width;
  65139. desiredHeight *= currentViewport.height;
  65140. }
  65141. }
  65142. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65143. if (!this._options.width) {
  65144. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65145. }
  65146. if (!this._options.height) {
  65147. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65148. }
  65149. }
  65150. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65151. if (this._textures.length > 0) {
  65152. for (var i = 0; i < this._textures.length; i++) {
  65153. this._engine._releaseTexture(this._textures.data[i]);
  65154. }
  65155. this._textures.reset();
  65156. }
  65157. this.width = desiredWidth;
  65158. this.height = desiredHeight;
  65159. var textureSize = { width: this.width, height: this.height };
  65160. var textureOptions = {
  65161. generateMipMaps: false,
  65162. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65163. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65164. samplingMode: this.renderTargetSamplingMode,
  65165. type: this._textureType
  65166. };
  65167. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65168. if (this._reusable) {
  65169. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65170. }
  65171. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65172. this.onSizeChangedObservable.notifyObservers(this);
  65173. }
  65174. this._textures.forEach(function (texture) {
  65175. if (texture.samples !== _this.samples) {
  65176. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65177. }
  65178. });
  65179. }
  65180. var target;
  65181. if (this._shareOutputWithPostProcess) {
  65182. target = this._shareOutputWithPostProcess.inputTexture;
  65183. }
  65184. else if (this._forcedOutputTexture) {
  65185. target = this._forcedOutputTexture;
  65186. this.width = this._forcedOutputTexture.width;
  65187. this.height = this._forcedOutputTexture.height;
  65188. }
  65189. else {
  65190. target = this.inputTexture;
  65191. }
  65192. // Bind the input of this post process to be used as the output of the previous post process.
  65193. if (this.enablePixelPerfectMode) {
  65194. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65195. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  65196. }
  65197. else {
  65198. this._scaleRatio.copyFromFloats(1, 1);
  65199. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  65200. }
  65201. this.onActivateObservable.notifyObservers(camera);
  65202. // Clear
  65203. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65204. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65205. }
  65206. if (this._reusable) {
  65207. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65208. }
  65209. return target;
  65210. };
  65211. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65212. /**
  65213. * If the post process is supported.
  65214. */
  65215. get: function () {
  65216. return this._effect.isSupported;
  65217. },
  65218. enumerable: true,
  65219. configurable: true
  65220. });
  65221. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65222. /**
  65223. * The aspect ratio of the output texture.
  65224. */
  65225. get: function () {
  65226. if (this._shareOutputWithPostProcess) {
  65227. return this._shareOutputWithPostProcess.aspectRatio;
  65228. }
  65229. if (this._forcedOutputTexture) {
  65230. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65231. }
  65232. return this.width / this.height;
  65233. },
  65234. enumerable: true,
  65235. configurable: true
  65236. });
  65237. /**
  65238. * Get a value indicating if the post-process is ready to be used
  65239. * @returns true if the post-process is ready (shader is compiled)
  65240. */
  65241. PostProcess.prototype.isReady = function () {
  65242. return this._effect && this._effect.isReady();
  65243. };
  65244. /**
  65245. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65246. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65247. */
  65248. PostProcess.prototype.apply = function () {
  65249. // Check
  65250. if (!this._effect || !this._effect.isReady())
  65251. return null;
  65252. // States
  65253. this._engine.enableEffect(this._effect);
  65254. this._engine.setState(false);
  65255. this._engine.setDepthBuffer(false);
  65256. this._engine.setDepthWrite(false);
  65257. // Alpha
  65258. this._engine.setAlphaMode(this.alphaMode);
  65259. if (this.alphaConstants) {
  65260. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65261. }
  65262. // Bind the output texture of the preivous post process as the input to this post process.
  65263. var source;
  65264. if (this._shareOutputWithPostProcess) {
  65265. source = this._shareOutputWithPostProcess.inputTexture;
  65266. }
  65267. else if (this._forcedOutputTexture) {
  65268. source = this._forcedOutputTexture;
  65269. }
  65270. else {
  65271. source = this.inputTexture;
  65272. }
  65273. this._effect._bindTexture("textureSampler", source);
  65274. // Parameters
  65275. this._effect.setVector2("scale", this._scaleRatio);
  65276. this.onApplyObservable.notifyObservers(this._effect);
  65277. return this._effect;
  65278. };
  65279. PostProcess.prototype._disposeTextures = function () {
  65280. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65281. return;
  65282. }
  65283. if (this._textures.length > 0) {
  65284. for (var i = 0; i < this._textures.length; i++) {
  65285. this._engine._releaseTexture(this._textures.data[i]);
  65286. }
  65287. }
  65288. this._textures.dispose();
  65289. };
  65290. /**
  65291. * Disposes the post process.
  65292. * @param camera The camera to dispose the post process on.
  65293. */
  65294. PostProcess.prototype.dispose = function (camera) {
  65295. camera = camera || this._camera;
  65296. this._disposeTextures();
  65297. if (this._scene) {
  65298. var index_1 = this._scene.postProcesses.indexOf(this);
  65299. if (index_1 !== -1) {
  65300. this._scene.postProcesses.splice(index_1, 1);
  65301. }
  65302. }
  65303. else {
  65304. var index_2 = this._engine.postProcesses.indexOf(this);
  65305. if (index_2 !== -1) {
  65306. this._engine.postProcesses.splice(index_2, 1);
  65307. }
  65308. }
  65309. if (!camera) {
  65310. return;
  65311. }
  65312. camera.detachPostProcess(this);
  65313. var index = camera._postProcesses.indexOf(this);
  65314. if (index === 0 && camera._postProcesses.length > 0) {
  65315. var firstPostProcess = this._camera._getFirstPostProcess();
  65316. if (firstPostProcess) {
  65317. firstPostProcess.markTextureDirty();
  65318. }
  65319. }
  65320. this.onActivateObservable.clear();
  65321. this.onAfterRenderObservable.clear();
  65322. this.onApplyObservable.clear();
  65323. this.onBeforeRenderObservable.clear();
  65324. this.onSizeChangedObservable.clear();
  65325. };
  65326. return PostProcess;
  65327. }());
  65328. BABYLON.PostProcess = PostProcess;
  65329. })(BABYLON || (BABYLON = {}));
  65330. //# sourceMappingURL=babylon.postProcess.js.map
  65331. var BABYLON;
  65332. (function (BABYLON) {
  65333. var PassPostProcess = /** @class */ (function (_super) {
  65334. __extends(PassPostProcess, _super);
  65335. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65336. if (camera === void 0) { camera = null; }
  65337. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65338. if (blockCompilation === void 0) { blockCompilation = false; }
  65339. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65340. }
  65341. return PassPostProcess;
  65342. }(BABYLON.PostProcess));
  65343. BABYLON.PassPostProcess = PassPostProcess;
  65344. })(BABYLON || (BABYLON = {}));
  65345. //# sourceMappingURL=babylon.passPostProcess.js.map
  65346. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65347. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65348. s = arguments[i];
  65349. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65350. t[p] = s[p];
  65351. }
  65352. return t;
  65353. };
  65354. var BABYLON;
  65355. (function (BABYLON) {
  65356. /**
  65357. * Default implementation IShadowGenerator.
  65358. * This is the main object responsible of generating shadows in the framework.
  65359. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65360. */
  65361. var ShadowGenerator = /** @class */ (function () {
  65362. /**
  65363. * Creates a ShadowGenerator object.
  65364. * A ShadowGenerator is the required tool to use the shadows.
  65365. * Each light casting shadows needs to use its own ShadowGenerator.
  65366. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65367. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65368. * @param light The light object generating the shadows.
  65369. * @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.
  65370. */
  65371. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65372. this._bias = 0.00005;
  65373. this._normalBias = 0;
  65374. this._blurBoxOffset = 1;
  65375. this._blurScale = 2;
  65376. this._blurKernel = 1;
  65377. this._useKernelBlur = false;
  65378. this._filter = ShadowGenerator.FILTER_NONE;
  65379. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65380. this._contactHardeningLightSizeUVRatio = 0.1;
  65381. this._darkness = 0;
  65382. this._transparencyShadow = false;
  65383. /**
  65384. * Controls the extent to which the shadows fade out at the edge of the frustum
  65385. * Used only by directionals and spots
  65386. */
  65387. this.frustumEdgeFalloff = 0;
  65388. /**
  65389. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65390. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65391. * It might on the other hand introduce peter panning.
  65392. */
  65393. this.forceBackFacesOnly = false;
  65394. this._lightDirection = BABYLON.Vector3.Zero();
  65395. this._viewMatrix = BABYLON.Matrix.Zero();
  65396. this._projectionMatrix = BABYLON.Matrix.Zero();
  65397. this._transformMatrix = BABYLON.Matrix.Zero();
  65398. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65399. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65400. this._currentFaceIndex = 0;
  65401. this._currentFaceIndexCache = 0;
  65402. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65403. this._mapSize = mapSize;
  65404. this._light = light;
  65405. this._scene = light.getScene();
  65406. light._shadowGenerator = this;
  65407. // Texture type fallback from float to int if not supported.
  65408. var caps = this._scene.getEngine().getCaps();
  65409. if (!useFullFloatFirst) {
  65410. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65411. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65412. }
  65413. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65414. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65415. }
  65416. else {
  65417. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65418. }
  65419. }
  65420. else {
  65421. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65422. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65423. }
  65424. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65425. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65426. }
  65427. else {
  65428. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65429. }
  65430. }
  65431. this._initializeGenerator();
  65432. this._applyFilterValues();
  65433. }
  65434. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65435. /**
  65436. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65437. */
  65438. get: function () {
  65439. return this._bias;
  65440. },
  65441. /**
  65442. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65443. */
  65444. set: function (bias) {
  65445. this._bias = bias;
  65446. },
  65447. enumerable: true,
  65448. configurable: true
  65449. });
  65450. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65451. /**
  65452. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65453. */
  65454. get: function () {
  65455. return this._normalBias;
  65456. },
  65457. /**
  65458. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65459. */
  65460. set: function (normalBias) {
  65461. this._normalBias = normalBias;
  65462. },
  65463. enumerable: true,
  65464. configurable: true
  65465. });
  65466. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65467. /**
  65468. * Gets the blur box offset: offset applied during the blur pass.
  65469. * Only usefull if useKernelBlur = false
  65470. */
  65471. get: function () {
  65472. return this._blurBoxOffset;
  65473. },
  65474. /**
  65475. * Sets the blur box offset: offset applied during the blur pass.
  65476. * Only usefull if useKernelBlur = false
  65477. */
  65478. set: function (value) {
  65479. if (this._blurBoxOffset === value) {
  65480. return;
  65481. }
  65482. this._blurBoxOffset = value;
  65483. this._disposeBlurPostProcesses();
  65484. },
  65485. enumerable: true,
  65486. configurable: true
  65487. });
  65488. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65489. /**
  65490. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65491. * 2 means half of the size.
  65492. */
  65493. get: function () {
  65494. return this._blurScale;
  65495. },
  65496. /**
  65497. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65498. * 2 means half of the size.
  65499. */
  65500. set: function (value) {
  65501. if (this._blurScale === value) {
  65502. return;
  65503. }
  65504. this._blurScale = value;
  65505. this._disposeBlurPostProcesses();
  65506. },
  65507. enumerable: true,
  65508. configurable: true
  65509. });
  65510. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65511. /**
  65512. * Gets the blur kernel: kernel size of the blur pass.
  65513. * Only usefull if useKernelBlur = true
  65514. */
  65515. get: function () {
  65516. return this._blurKernel;
  65517. },
  65518. /**
  65519. * Sets the blur kernel: kernel size of the blur pass.
  65520. * Only usefull if useKernelBlur = true
  65521. */
  65522. set: function (value) {
  65523. if (this._blurKernel === value) {
  65524. return;
  65525. }
  65526. this._blurKernel = value;
  65527. this._disposeBlurPostProcesses();
  65528. },
  65529. enumerable: true,
  65530. configurable: true
  65531. });
  65532. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65533. /**
  65534. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65535. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65536. */
  65537. get: function () {
  65538. return this._useKernelBlur;
  65539. },
  65540. /**
  65541. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65542. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65543. */
  65544. set: function (value) {
  65545. if (this._useKernelBlur === value) {
  65546. return;
  65547. }
  65548. this._useKernelBlur = value;
  65549. this._disposeBlurPostProcesses();
  65550. },
  65551. enumerable: true,
  65552. configurable: true
  65553. });
  65554. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65555. /**
  65556. * Gets the depth scale used in ESM mode.
  65557. */
  65558. get: function () {
  65559. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65560. },
  65561. /**
  65562. * Sets the depth scale used in ESM mode.
  65563. * This can override the scale stored on the light.
  65564. */
  65565. set: function (value) {
  65566. this._depthScale = value;
  65567. },
  65568. enumerable: true,
  65569. configurable: true
  65570. });
  65571. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65572. /**
  65573. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65574. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65575. */
  65576. get: function () {
  65577. return this._filter;
  65578. },
  65579. /**
  65580. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65581. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65582. */
  65583. set: function (value) {
  65584. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65585. if (this._light.needCube()) {
  65586. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65587. this.useExponentialShadowMap = true;
  65588. return;
  65589. }
  65590. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65591. this.useCloseExponentialShadowMap = true;
  65592. return;
  65593. }
  65594. // PCF on cubemap would also be expensive
  65595. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65596. this.usePoissonSampling = true;
  65597. return;
  65598. }
  65599. }
  65600. // Weblg1 fallback for PCF.
  65601. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65602. if (this._scene.getEngine().webGLVersion === 1) {
  65603. this.usePoissonSampling = true;
  65604. return;
  65605. }
  65606. }
  65607. if (this._filter === value) {
  65608. return;
  65609. }
  65610. this._filter = value;
  65611. this._disposeBlurPostProcesses();
  65612. this._applyFilterValues();
  65613. this._light._markMeshesAsLightDirty();
  65614. },
  65615. enumerable: true,
  65616. configurable: true
  65617. });
  65618. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65619. /**
  65620. * Gets if the current filter is set to Poisson Sampling.
  65621. */
  65622. get: function () {
  65623. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65624. },
  65625. /**
  65626. * Sets the current filter to Poisson Sampling.
  65627. */
  65628. set: function (value) {
  65629. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65630. return;
  65631. }
  65632. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65633. },
  65634. enumerable: true,
  65635. configurable: true
  65636. });
  65637. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65638. /**
  65639. * Gets if the current filter is set to VSM.
  65640. * DEPRECATED. Should use useExponentialShadowMap instead.
  65641. */
  65642. get: function () {
  65643. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65644. return this.useExponentialShadowMap;
  65645. },
  65646. /**
  65647. * Sets the current filter is to VSM.
  65648. * DEPRECATED. Should use useExponentialShadowMap instead.
  65649. */
  65650. set: function (value) {
  65651. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65652. this.useExponentialShadowMap = value;
  65653. },
  65654. enumerable: true,
  65655. configurable: true
  65656. });
  65657. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65658. /**
  65659. * Gets if the current filter is set to blurred VSM.
  65660. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65661. */
  65662. get: function () {
  65663. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65664. return this.useBlurExponentialShadowMap;
  65665. },
  65666. /**
  65667. * Sets the current filter is to blurred VSM.
  65668. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65669. */
  65670. set: function (value) {
  65671. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65672. this.useBlurExponentialShadowMap = value;
  65673. },
  65674. enumerable: true,
  65675. configurable: true
  65676. });
  65677. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65678. /**
  65679. * Gets if the current filter is set to ESM.
  65680. */
  65681. get: function () {
  65682. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65683. },
  65684. /**
  65685. * Sets the current filter is to ESM.
  65686. */
  65687. set: function (value) {
  65688. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65689. return;
  65690. }
  65691. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65692. },
  65693. enumerable: true,
  65694. configurable: true
  65695. });
  65696. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65697. /**
  65698. * Gets if the current filter is set to filtered ESM.
  65699. */
  65700. get: function () {
  65701. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65702. },
  65703. /**
  65704. * Gets if the current filter is set to filtered ESM.
  65705. */
  65706. set: function (value) {
  65707. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65708. return;
  65709. }
  65710. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65711. },
  65712. enumerable: true,
  65713. configurable: true
  65714. });
  65715. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65716. /**
  65717. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65718. * exponential to prevent steep falloff artifacts).
  65719. */
  65720. get: function () {
  65721. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65722. },
  65723. /**
  65724. * Sets the current filter to "close ESM" (using the inverse of the
  65725. * exponential to prevent steep falloff artifacts).
  65726. */
  65727. set: function (value) {
  65728. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65729. return;
  65730. }
  65731. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65732. },
  65733. enumerable: true,
  65734. configurable: true
  65735. });
  65736. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65737. /**
  65738. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65739. * exponential to prevent steep falloff artifacts).
  65740. */
  65741. get: function () {
  65742. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65743. },
  65744. /**
  65745. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65746. * exponential to prevent steep falloff artifacts).
  65747. */
  65748. set: function (value) {
  65749. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65750. return;
  65751. }
  65752. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65753. },
  65754. enumerable: true,
  65755. configurable: true
  65756. });
  65757. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65758. /**
  65759. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65760. */
  65761. get: function () {
  65762. return this.filter === ShadowGenerator.FILTER_PCF;
  65763. },
  65764. /**
  65765. * Sets the current filter to "PCF" (percentage closer filtering).
  65766. */
  65767. set: function (value) {
  65768. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65769. return;
  65770. }
  65771. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65772. },
  65773. enumerable: true,
  65774. configurable: true
  65775. });
  65776. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65777. /**
  65778. * Gets the PCF or PCSS Quality.
  65779. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65780. */
  65781. get: function () {
  65782. return this._filteringQuality;
  65783. },
  65784. /**
  65785. * Sets the PCF or PCSS Quality.
  65786. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65787. */
  65788. set: function (filteringQuality) {
  65789. this._filteringQuality = filteringQuality;
  65790. },
  65791. enumerable: true,
  65792. configurable: true
  65793. });
  65794. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65795. /**
  65796. * Gets if the current filter is set to "PCSS" (contact hardening).
  65797. */
  65798. get: function () {
  65799. return this.filter === ShadowGenerator.FILTER_PCSS;
  65800. },
  65801. /**
  65802. * Sets the current filter to "PCSS" (contact hardening).
  65803. */
  65804. set: function (value) {
  65805. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65806. return;
  65807. }
  65808. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65809. },
  65810. enumerable: true,
  65811. configurable: true
  65812. });
  65813. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65814. /**
  65815. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65816. * Using a ratio helps keeping shape stability independently of the map size.
  65817. *
  65818. * It does not account for the light projection as it was having too much
  65819. * instability during the light setup or during light position changes.
  65820. *
  65821. * Only valid if useContactHardeningShadow is true.
  65822. */
  65823. get: function () {
  65824. return this._contactHardeningLightSizeUVRatio;
  65825. },
  65826. /**
  65827. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65828. * Using a ratio helps keeping shape stability independently of the map size.
  65829. *
  65830. * It does not account for the light projection as it was having too much
  65831. * instability during the light setup or during light position changes.
  65832. *
  65833. * Only valid if useContactHardeningShadow is true.
  65834. */
  65835. set: function (contactHardeningLightSizeUVRatio) {
  65836. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65837. },
  65838. enumerable: true,
  65839. configurable: true
  65840. });
  65841. /**
  65842. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65843. * 0 means strongest and 1 would means no shadow.
  65844. * @returns the darkness.
  65845. */
  65846. ShadowGenerator.prototype.getDarkness = function () {
  65847. return this._darkness;
  65848. };
  65849. /**
  65850. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65851. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65852. * @returns the shadow generator allowing fluent coding.
  65853. */
  65854. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65855. if (darkness >= 1.0)
  65856. this._darkness = 1.0;
  65857. else if (darkness <= 0.0)
  65858. this._darkness = 0.0;
  65859. else
  65860. this._darkness = darkness;
  65861. return this;
  65862. };
  65863. /**
  65864. * Sets the ability to have transparent shadow (boolean).
  65865. * @param transparent True if transparent else False
  65866. * @returns the shadow generator allowing fluent coding
  65867. */
  65868. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65869. this._transparencyShadow = transparent;
  65870. return this;
  65871. };
  65872. /**
  65873. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65874. * @returns The render target texture if present otherwise, null
  65875. */
  65876. ShadowGenerator.prototype.getShadowMap = function () {
  65877. return this._shadowMap;
  65878. };
  65879. /**
  65880. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65881. * @returns The render target texture if the shadow map is present otherwise, null
  65882. */
  65883. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65884. if (this._shadowMap2) {
  65885. return this._shadowMap2;
  65886. }
  65887. return this._shadowMap;
  65888. };
  65889. /**
  65890. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65891. * @param mesh Mesh to add
  65892. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65893. * @returns the Shadow Generator itself
  65894. */
  65895. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65896. if (includeDescendants === void 0) { includeDescendants = true; }
  65897. if (!this._shadowMap) {
  65898. return this;
  65899. }
  65900. if (!this._shadowMap.renderList) {
  65901. this._shadowMap.renderList = [];
  65902. }
  65903. this._shadowMap.renderList.push(mesh);
  65904. if (includeDescendants) {
  65905. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65906. }
  65907. return this;
  65908. var _a;
  65909. };
  65910. /**
  65911. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65912. * @param mesh Mesh to remove
  65913. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65914. * @returns the Shadow Generator itself
  65915. */
  65916. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65917. if (includeDescendants === void 0) { includeDescendants = true; }
  65918. if (!this._shadowMap || !this._shadowMap.renderList) {
  65919. return this;
  65920. }
  65921. var index = this._shadowMap.renderList.indexOf(mesh);
  65922. if (index !== -1) {
  65923. this._shadowMap.renderList.splice(index, 1);
  65924. }
  65925. if (includeDescendants) {
  65926. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65927. var child = _a[_i];
  65928. this.removeShadowCaster(child);
  65929. }
  65930. }
  65931. return this;
  65932. };
  65933. /**
  65934. * Returns the associated light object.
  65935. * @returns the light generating the shadow
  65936. */
  65937. ShadowGenerator.prototype.getLight = function () {
  65938. return this._light;
  65939. };
  65940. ShadowGenerator.prototype._initializeGenerator = function () {
  65941. this._light._markMeshesAsLightDirty();
  65942. this._initializeShadowMap();
  65943. };
  65944. ShadowGenerator.prototype._initializeShadowMap = function () {
  65945. var _this = this;
  65946. // Render target
  65947. var engine = this._scene.getEngine();
  65948. if (engine.webGLVersion > 1) {
  65949. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65950. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65951. }
  65952. else {
  65953. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65954. }
  65955. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65956. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65957. this._shadowMap.anisotropicFilteringLevel = 1;
  65958. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65959. this._shadowMap.renderParticles = false;
  65960. this._shadowMap.ignoreCameraViewport = true;
  65961. // Record Face Index before render.
  65962. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65963. _this._currentFaceIndex = faceIndex;
  65964. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65965. engine.setColorWrite(false);
  65966. }
  65967. });
  65968. // Custom render function.
  65969. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65970. // Blur if required afer render.
  65971. this._shadowMap.onAfterUnbindObservable.add(function () {
  65972. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65973. engine.setColorWrite(true);
  65974. }
  65975. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65976. return;
  65977. }
  65978. var shadowMap = _this.getShadowMapForRendering();
  65979. if (shadowMap) {
  65980. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65981. }
  65982. });
  65983. // Clear according to the chosen filter.
  65984. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65985. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65986. this._shadowMap.onClearObservable.add(function (engine) {
  65987. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65988. engine.clear(clearOne, false, true, false);
  65989. }
  65990. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65991. engine.clear(clearZero, true, true, false);
  65992. }
  65993. else {
  65994. engine.clear(clearOne, true, true, false);
  65995. }
  65996. });
  65997. };
  65998. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65999. var _this = this;
  66000. var engine = this._scene.getEngine();
  66001. var targetSize = this._mapSize / this.blurScale;
  66002. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66003. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66004. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66005. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66006. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66007. }
  66008. if (this.useKernelBlur) {
  66009. 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);
  66010. this._kernelBlurXPostprocess.width = targetSize;
  66011. this._kernelBlurXPostprocess.height = targetSize;
  66012. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66013. effect.setTexture("textureSampler", _this._shadowMap);
  66014. });
  66015. 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);
  66016. this._kernelBlurXPostprocess.autoClear = false;
  66017. this._kernelBlurYPostprocess.autoClear = false;
  66018. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66019. this._kernelBlurXPostprocess.packedFloat = true;
  66020. this._kernelBlurYPostprocess.packedFloat = true;
  66021. }
  66022. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66023. }
  66024. else {
  66025. 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);
  66026. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66027. effect.setFloat2("screenSize", targetSize, targetSize);
  66028. effect.setTexture("textureSampler", _this._shadowMap);
  66029. });
  66030. this._boxBlurPostprocess.autoClear = false;
  66031. this._blurPostProcesses = [this._boxBlurPostprocess];
  66032. }
  66033. };
  66034. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66035. var index;
  66036. var engine = this._scene.getEngine();
  66037. if (depthOnlySubMeshes.length) {
  66038. engine.setColorWrite(false);
  66039. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66040. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66041. }
  66042. engine.setColorWrite(true);
  66043. }
  66044. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66045. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66046. }
  66047. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66048. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66049. }
  66050. if (this._transparencyShadow) {
  66051. for (index = 0; index < transparentSubMeshes.length; index++) {
  66052. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66053. }
  66054. }
  66055. };
  66056. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66057. var _this = this;
  66058. var mesh = subMesh.getRenderingMesh();
  66059. var scene = this._scene;
  66060. var engine = scene.getEngine();
  66061. var material = subMesh.getMaterial();
  66062. if (!material) {
  66063. return;
  66064. }
  66065. // Culling
  66066. engine.setState(material.backFaceCulling);
  66067. // Managing instances
  66068. var batch = mesh._getInstancesRenderList(subMesh._id);
  66069. if (batch.mustReturn) {
  66070. return;
  66071. }
  66072. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66073. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66074. engine.enableEffect(this._effect);
  66075. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66076. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66077. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66078. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66079. this._effect.setVector3("lightData", this._cachedDirection);
  66080. }
  66081. else {
  66082. this._effect.setVector3("lightData", this._cachedPosition);
  66083. }
  66084. if (scene.activeCamera) {
  66085. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66086. }
  66087. // Alpha test
  66088. if (material && material.needAlphaTesting()) {
  66089. var alphaTexture = material.getAlphaTestTexture();
  66090. if (alphaTexture) {
  66091. this._effect.setTexture("diffuseSampler", alphaTexture);
  66092. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66093. }
  66094. }
  66095. // Bones
  66096. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66097. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66098. }
  66099. // Morph targets
  66100. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66101. if (this.forceBackFacesOnly) {
  66102. engine.setState(true, 0, false, true);
  66103. }
  66104. // Draw
  66105. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66106. if (this.forceBackFacesOnly) {
  66107. engine.setState(true, 0, false, false);
  66108. }
  66109. }
  66110. else {
  66111. // Need to reset refresh rate of the shadowMap
  66112. if (this._shadowMap) {
  66113. this._shadowMap.resetRefreshCounter();
  66114. }
  66115. }
  66116. };
  66117. ShadowGenerator.prototype._applyFilterValues = function () {
  66118. if (!this._shadowMap) {
  66119. return;
  66120. }
  66121. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66122. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66123. }
  66124. else {
  66125. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66126. }
  66127. };
  66128. /**
  66129. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66130. * @param onCompiled Callback triggered at the and of the effects compilation
  66131. * @param options Sets of optional options forcing the compilation with different modes
  66132. */
  66133. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66134. var _this = this;
  66135. var localOptions = __assign({ useInstances: false }, options);
  66136. var shadowMap = this.getShadowMap();
  66137. if (!shadowMap) {
  66138. if (onCompiled) {
  66139. onCompiled(this);
  66140. }
  66141. return;
  66142. }
  66143. var renderList = shadowMap.renderList;
  66144. if (!renderList) {
  66145. if (onCompiled) {
  66146. onCompiled(this);
  66147. }
  66148. return;
  66149. }
  66150. var subMeshes = new Array();
  66151. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66152. var mesh = renderList_1[_i];
  66153. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66154. }
  66155. if (subMeshes.length === 0) {
  66156. if (onCompiled) {
  66157. onCompiled(this);
  66158. }
  66159. return;
  66160. }
  66161. var currentIndex = 0;
  66162. var checkReady = function () {
  66163. if (!_this._scene || !_this._scene.getEngine()) {
  66164. return;
  66165. }
  66166. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66167. currentIndex++;
  66168. if (currentIndex >= subMeshes.length) {
  66169. if (onCompiled) {
  66170. onCompiled(_this);
  66171. }
  66172. return;
  66173. }
  66174. }
  66175. setTimeout(checkReady, 16);
  66176. };
  66177. checkReady();
  66178. };
  66179. /**
  66180. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66181. * @param options Sets of optional options forcing the compilation with different modes
  66182. * @returns A promise that resolves when the compilation completes
  66183. */
  66184. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66185. var _this = this;
  66186. return new Promise(function (resolve) {
  66187. _this.forceCompilation(function () {
  66188. resolve();
  66189. }, options);
  66190. });
  66191. };
  66192. /**
  66193. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66194. * @param subMesh The submesh we want to render in the shadow map
  66195. * @param useInstances Defines wether will draw in the map using instances
  66196. * @returns true if ready otherwise, false
  66197. */
  66198. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66199. var defines = [];
  66200. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66201. defines.push("#define FLOAT");
  66202. }
  66203. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66204. defines.push("#define ESM");
  66205. }
  66206. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66207. defines.push("#define DEPTHTEXTURE");
  66208. }
  66209. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66210. var mesh = subMesh.getMesh();
  66211. var material = subMesh.getMaterial();
  66212. // Normal bias.
  66213. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66214. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66215. defines.push("#define NORMAL");
  66216. if (mesh.nonUniformScaling) {
  66217. defines.push("#define NONUNIFORMSCALING");
  66218. }
  66219. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66220. defines.push("#define DIRECTIONINLIGHTDATA");
  66221. }
  66222. }
  66223. // Alpha test
  66224. if (material && material.needAlphaTesting()) {
  66225. var alphaTexture = material.getAlphaTestTexture();
  66226. if (alphaTexture) {
  66227. defines.push("#define ALPHATEST");
  66228. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66229. attribs.push(BABYLON.VertexBuffer.UVKind);
  66230. defines.push("#define UV1");
  66231. }
  66232. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66233. if (alphaTexture.coordinatesIndex === 1) {
  66234. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66235. defines.push("#define UV2");
  66236. }
  66237. }
  66238. }
  66239. }
  66240. // Bones
  66241. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66242. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66243. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66244. if (mesh.numBoneInfluencers > 4) {
  66245. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66246. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66247. }
  66248. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66249. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66250. }
  66251. else {
  66252. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66253. }
  66254. // Morph targets
  66255. var manager = mesh.morphTargetManager;
  66256. var morphInfluencers = 0;
  66257. if (manager) {
  66258. if (manager.numInfluencers > 0) {
  66259. defines.push("#define MORPHTARGETS");
  66260. morphInfluencers = manager.numInfluencers;
  66261. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66262. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66263. }
  66264. }
  66265. // Instances
  66266. if (useInstances) {
  66267. defines.push("#define INSTANCES");
  66268. attribs.push("world0");
  66269. attribs.push("world1");
  66270. attribs.push("world2");
  66271. attribs.push("world3");
  66272. }
  66273. // Get correct effect
  66274. var join = defines.join("\n");
  66275. if (this._cachedDefines !== join) {
  66276. this._cachedDefines = join;
  66277. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66278. }
  66279. if (!this._effect.isReady()) {
  66280. return false;
  66281. }
  66282. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66283. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66284. this._initializeBlurRTTAndPostProcesses();
  66285. }
  66286. }
  66287. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66288. return false;
  66289. }
  66290. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66291. return false;
  66292. }
  66293. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66294. return false;
  66295. }
  66296. return true;
  66297. };
  66298. /**
  66299. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66300. * @param defines Defines of the material we want to update
  66301. * @param lightIndex Index of the light in the enabled light list of the material
  66302. */
  66303. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66304. var scene = this._scene;
  66305. var light = this._light;
  66306. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66307. return;
  66308. }
  66309. defines["SHADOW" + lightIndex] = true;
  66310. if (this.useContactHardeningShadow) {
  66311. defines["SHADOWPCSS" + lightIndex] = true;
  66312. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66313. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66314. }
  66315. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66316. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66317. }
  66318. // else default to high.
  66319. }
  66320. if (this.usePercentageCloserFiltering) {
  66321. defines["SHADOWPCF" + lightIndex] = true;
  66322. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66323. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66324. }
  66325. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66326. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66327. }
  66328. // else default to high.
  66329. }
  66330. else if (this.usePoissonSampling) {
  66331. defines["SHADOWPOISSON" + lightIndex] = true;
  66332. }
  66333. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66334. defines["SHADOWESM" + lightIndex] = true;
  66335. }
  66336. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66337. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66338. }
  66339. if (light.needCube()) {
  66340. defines["SHADOWCUBE" + lightIndex] = true;
  66341. }
  66342. };
  66343. /**
  66344. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66345. * defined in the generator but impacting the effect).
  66346. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66347. * @param effect The effect we are binfing the information for
  66348. */
  66349. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66350. var light = this._light;
  66351. var scene = this._scene;
  66352. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66353. return;
  66354. }
  66355. var camera = scene.activeCamera;
  66356. if (!camera) {
  66357. return;
  66358. }
  66359. var shadowMap = this.getShadowMap();
  66360. if (!shadowMap) {
  66361. return;
  66362. }
  66363. if (!light.needCube()) {
  66364. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66365. }
  66366. // Only PCF uses depth stencil texture.
  66367. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66368. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66369. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66370. }
  66371. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66372. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66373. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66374. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66375. }
  66376. else {
  66377. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66378. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66379. }
  66380. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66381. };
  66382. /**
  66383. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66384. * (eq to shadow prjection matrix * light transform matrix)
  66385. * @returns The transform matrix used to create the shadow map
  66386. */
  66387. ShadowGenerator.prototype.getTransformMatrix = function () {
  66388. var scene = this._scene;
  66389. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66390. return this._transformMatrix;
  66391. }
  66392. this._currentRenderID = scene.getRenderId();
  66393. this._currentFaceIndexCache = this._currentFaceIndex;
  66394. var lightPosition = this._light.position;
  66395. if (this._light.computeTransformedInformation()) {
  66396. lightPosition = this._light.transformedPosition;
  66397. }
  66398. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66399. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66400. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66401. }
  66402. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66403. this._cachedPosition.copyFrom(lightPosition);
  66404. this._cachedDirection.copyFrom(this._lightDirection);
  66405. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66406. var shadowMap = this.getShadowMap();
  66407. if (shadowMap) {
  66408. var renderList = shadowMap.renderList;
  66409. if (renderList) {
  66410. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66411. }
  66412. }
  66413. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66414. }
  66415. return this._transformMatrix;
  66416. };
  66417. /**
  66418. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66419. * Cube and 2D textures for instance.
  66420. */
  66421. ShadowGenerator.prototype.recreateShadowMap = function () {
  66422. var shadowMap = this._shadowMap;
  66423. if (!shadowMap) {
  66424. return;
  66425. }
  66426. // Track render list.
  66427. var renderList = shadowMap.renderList;
  66428. // Clean up existing data.
  66429. this._disposeRTTandPostProcesses();
  66430. // Reinitializes.
  66431. this._initializeGenerator();
  66432. // Reaffect the filter to ensure a correct fallback if necessary.
  66433. this.filter = this.filter;
  66434. // Reaffect the filter.
  66435. this._applyFilterValues();
  66436. // Reaffect Render List.
  66437. this._shadowMap.renderList = renderList;
  66438. };
  66439. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66440. if (this._shadowMap2) {
  66441. this._shadowMap2.dispose();
  66442. this._shadowMap2 = null;
  66443. }
  66444. if (this._boxBlurPostprocess) {
  66445. this._boxBlurPostprocess.dispose();
  66446. this._boxBlurPostprocess = null;
  66447. }
  66448. if (this._kernelBlurXPostprocess) {
  66449. this._kernelBlurXPostprocess.dispose();
  66450. this._kernelBlurXPostprocess = null;
  66451. }
  66452. if (this._kernelBlurYPostprocess) {
  66453. this._kernelBlurYPostprocess.dispose();
  66454. this._kernelBlurYPostprocess = null;
  66455. }
  66456. this._blurPostProcesses = [];
  66457. };
  66458. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66459. if (this._shadowMap) {
  66460. this._shadowMap.dispose();
  66461. this._shadowMap = null;
  66462. }
  66463. this._disposeBlurPostProcesses();
  66464. };
  66465. /**
  66466. * Disposes the ShadowGenerator.
  66467. * Returns nothing.
  66468. */
  66469. ShadowGenerator.prototype.dispose = function () {
  66470. this._disposeRTTandPostProcesses();
  66471. if (this._light) {
  66472. this._light._shadowGenerator = null;
  66473. this._light._markMeshesAsLightDirty();
  66474. }
  66475. };
  66476. /**
  66477. * Serializes the shadow generator setup to a json object.
  66478. * @returns The serialized JSON object
  66479. */
  66480. ShadowGenerator.prototype.serialize = function () {
  66481. var serializationObject = {};
  66482. var shadowMap = this.getShadowMap();
  66483. if (!shadowMap) {
  66484. return serializationObject;
  66485. }
  66486. serializationObject.lightId = this._light.id;
  66487. serializationObject.mapSize = shadowMap.getRenderSize();
  66488. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66489. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66490. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66491. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66492. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66493. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66494. serializationObject.depthScale = this.depthScale;
  66495. serializationObject.darkness = this.getDarkness();
  66496. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66497. serializationObject.blurKernel = this.blurKernel;
  66498. serializationObject.blurScale = this.blurScale;
  66499. serializationObject.useKernelBlur = this.useKernelBlur;
  66500. serializationObject.transparencyShadow = this._transparencyShadow;
  66501. serializationObject.bias = this.bias;
  66502. serializationObject.normalBias = this.normalBias;
  66503. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66504. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66505. serializationObject.filteringQuality = this.filteringQuality;
  66506. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66507. serializationObject.renderList = [];
  66508. if (shadowMap.renderList) {
  66509. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66510. var mesh = shadowMap.renderList[meshIndex];
  66511. serializationObject.renderList.push(mesh.id);
  66512. }
  66513. }
  66514. return serializationObject;
  66515. };
  66516. /**
  66517. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66518. * @param parsedShadowGenerator The JSON object to parse
  66519. * @param scene The scene to create the shadow map for
  66520. * @returns The parsed shadow generator
  66521. */
  66522. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66523. //casting to point light, as light is missing the position attr and typescript complains.
  66524. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66525. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66526. var shadowMap = shadowGenerator.getShadowMap();
  66527. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66528. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66529. meshes.forEach(function (mesh) {
  66530. if (!shadowMap) {
  66531. return;
  66532. }
  66533. if (!shadowMap.renderList) {
  66534. shadowMap.renderList = [];
  66535. }
  66536. shadowMap.renderList.push(mesh);
  66537. });
  66538. }
  66539. if (parsedShadowGenerator.usePoissonSampling) {
  66540. shadowGenerator.usePoissonSampling = true;
  66541. }
  66542. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66543. shadowGenerator.useExponentialShadowMap = true;
  66544. }
  66545. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66546. shadowGenerator.useBlurExponentialShadowMap = true;
  66547. }
  66548. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66549. shadowGenerator.useCloseExponentialShadowMap = true;
  66550. }
  66551. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66552. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66553. }
  66554. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66555. shadowGenerator.usePercentageCloserFiltering = true;
  66556. }
  66557. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66558. shadowGenerator.useContactHardeningShadow = true;
  66559. }
  66560. if (parsedShadowGenerator.filteringQuality) {
  66561. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66562. }
  66563. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66564. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66565. }
  66566. // Backward compat
  66567. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66568. shadowGenerator.useExponentialShadowMap = true;
  66569. }
  66570. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66571. shadowGenerator.useBlurExponentialShadowMap = true;
  66572. }
  66573. if (parsedShadowGenerator.depthScale) {
  66574. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66575. }
  66576. if (parsedShadowGenerator.blurScale) {
  66577. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66578. }
  66579. if (parsedShadowGenerator.blurBoxOffset) {
  66580. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66581. }
  66582. if (parsedShadowGenerator.useKernelBlur) {
  66583. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66584. }
  66585. if (parsedShadowGenerator.blurKernel) {
  66586. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66587. }
  66588. if (parsedShadowGenerator.bias !== undefined) {
  66589. shadowGenerator.bias = parsedShadowGenerator.bias;
  66590. }
  66591. if (parsedShadowGenerator.normalBias !== undefined) {
  66592. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66593. }
  66594. if (parsedShadowGenerator.darkness) {
  66595. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66596. }
  66597. if (parsedShadowGenerator.transparencyShadow) {
  66598. shadowGenerator.setTransparencyShadow(true);
  66599. }
  66600. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66601. return shadowGenerator;
  66602. };
  66603. /**
  66604. * Shadow generator mode None: no filtering applied.
  66605. */
  66606. ShadowGenerator.FILTER_NONE = 0;
  66607. /**
  66608. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66609. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66610. */
  66611. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66612. /**
  66613. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66614. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66615. */
  66616. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66617. /**
  66618. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66619. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66620. */
  66621. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66622. /**
  66623. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66624. * edge artifacts on steep falloff.
  66625. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66626. */
  66627. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66628. /**
  66629. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66630. * edge artifacts on steep falloff.
  66631. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66632. */
  66633. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66634. /**
  66635. * Shadow generator mode PCF: Percentage Closer Filtering
  66636. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66637. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66638. */
  66639. ShadowGenerator.FILTER_PCF = 6;
  66640. /**
  66641. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66642. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66643. * Contact Hardening
  66644. */
  66645. ShadowGenerator.FILTER_PCSS = 7;
  66646. /**
  66647. * Reserved for PCF and PCSS
  66648. * Highest Quality.
  66649. *
  66650. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66651. *
  66652. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66653. */
  66654. ShadowGenerator.QUALITY_HIGH = 0;
  66655. /**
  66656. * Reserved for PCF and PCSS
  66657. * Good tradeoff for quality/perf cross devices
  66658. *
  66659. * Execute PCF on a 3*3 kernel.
  66660. *
  66661. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66662. */
  66663. ShadowGenerator.QUALITY_MEDIUM = 1;
  66664. /**
  66665. * Reserved for PCF and PCSS
  66666. * The lowest quality but the fastest.
  66667. *
  66668. * Execute PCF on a 1*1 kernel.
  66669. *
  66670. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66671. */
  66672. ShadowGenerator.QUALITY_LOW = 2;
  66673. return ShadowGenerator;
  66674. }());
  66675. BABYLON.ShadowGenerator = ShadowGenerator;
  66676. })(BABYLON || (BABYLON = {}));
  66677. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66678. var BABYLON;
  66679. (function (BABYLON) {
  66680. var DefaultLoadingScreen = /** @class */ (function () {
  66681. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66682. if (_loadingText === void 0) { _loadingText = ""; }
  66683. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66684. var _this = this;
  66685. this._renderingCanvas = _renderingCanvas;
  66686. this._loadingText = _loadingText;
  66687. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66688. // Resize
  66689. this._resizeLoadingUI = function () {
  66690. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66691. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66692. if (!_this._loadingDiv) {
  66693. return;
  66694. }
  66695. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66696. _this._loadingDiv.style.left = canvasRect.left + "px";
  66697. _this._loadingDiv.style.top = canvasRect.top + "px";
  66698. _this._loadingDiv.style.width = canvasRect.width + "px";
  66699. _this._loadingDiv.style.height = canvasRect.height + "px";
  66700. };
  66701. }
  66702. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66703. if (this._loadingDiv) {
  66704. // Do not add a loading screen if there is already one
  66705. return;
  66706. }
  66707. this._loadingDiv = document.createElement("div");
  66708. this._loadingDiv.id = "babylonjsLoadingDiv";
  66709. this._loadingDiv.style.opacity = "0";
  66710. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66711. this._loadingDiv.style.pointerEvents = "none";
  66712. // Loading text
  66713. this._loadingTextDiv = document.createElement("div");
  66714. this._loadingTextDiv.style.position = "absolute";
  66715. this._loadingTextDiv.style.left = "0";
  66716. this._loadingTextDiv.style.top = "50%";
  66717. this._loadingTextDiv.style.marginTop = "80px";
  66718. this._loadingTextDiv.style.width = "100%";
  66719. this._loadingTextDiv.style.height = "20px";
  66720. this._loadingTextDiv.style.fontFamily = "Arial";
  66721. this._loadingTextDiv.style.fontSize = "14px";
  66722. this._loadingTextDiv.style.color = "white";
  66723. this._loadingTextDiv.style.textAlign = "center";
  66724. this._loadingTextDiv.innerHTML = "Loading";
  66725. this._loadingDiv.appendChild(this._loadingTextDiv);
  66726. //set the predefined text
  66727. this._loadingTextDiv.innerHTML = this._loadingText;
  66728. // Generating keyframes
  66729. var style = document.createElement('style');
  66730. style.type = 'text/css';
  66731. 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 }";
  66732. style.innerHTML = keyFrames;
  66733. document.getElementsByTagName('head')[0].appendChild(style);
  66734. // Loading img
  66735. var imgBack = new Image();
  66736. 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";
  66737. imgBack.style.position = "absolute";
  66738. imgBack.style.left = "50%";
  66739. imgBack.style.top = "50%";
  66740. imgBack.style.marginLeft = "-60px";
  66741. imgBack.style.marginTop = "-60px";
  66742. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66743. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66744. imgBack.style.transformOrigin = "50% 50%";
  66745. imgBack.style.webkitTransformOrigin = "50% 50%";
  66746. this._loadingDiv.appendChild(imgBack);
  66747. this._resizeLoadingUI();
  66748. window.addEventListener("resize", this._resizeLoadingUI);
  66749. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66750. document.body.appendChild(this._loadingDiv);
  66751. this._loadingDiv.style.opacity = "1";
  66752. };
  66753. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66754. var _this = this;
  66755. if (!this._loadingDiv) {
  66756. return;
  66757. }
  66758. var onTransitionEnd = function () {
  66759. if (!_this._loadingDiv) {
  66760. return;
  66761. }
  66762. document.body.removeChild(_this._loadingDiv);
  66763. window.removeEventListener("resize", _this._resizeLoadingUI);
  66764. _this._loadingDiv = null;
  66765. };
  66766. this._loadingDiv.style.opacity = "0";
  66767. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66768. };
  66769. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66770. set: function (text) {
  66771. this._loadingText = text;
  66772. if (this._loadingTextDiv) {
  66773. this._loadingTextDiv.innerHTML = this._loadingText;
  66774. }
  66775. },
  66776. enumerable: true,
  66777. configurable: true
  66778. });
  66779. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66780. get: function () {
  66781. return this._loadingDivBackgroundColor;
  66782. },
  66783. set: function (color) {
  66784. this._loadingDivBackgroundColor = color;
  66785. if (!this._loadingDiv) {
  66786. return;
  66787. }
  66788. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66789. },
  66790. enumerable: true,
  66791. configurable: true
  66792. });
  66793. return DefaultLoadingScreen;
  66794. }());
  66795. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66796. })(BABYLON || (BABYLON = {}));
  66797. //# sourceMappingURL=babylon.loadingScreen.js.map
  66798. var BABYLON;
  66799. (function (BABYLON) {
  66800. var SceneLoaderProgressEvent = /** @class */ (function () {
  66801. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66802. this.lengthComputable = lengthComputable;
  66803. this.loaded = loaded;
  66804. this.total = total;
  66805. }
  66806. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66807. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66808. };
  66809. return SceneLoaderProgressEvent;
  66810. }());
  66811. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66812. var SceneLoader = /** @class */ (function () {
  66813. function SceneLoader() {
  66814. }
  66815. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66816. get: function () {
  66817. return 0;
  66818. },
  66819. enumerable: true,
  66820. configurable: true
  66821. });
  66822. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66823. get: function () {
  66824. return 1;
  66825. },
  66826. enumerable: true,
  66827. configurable: true
  66828. });
  66829. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66830. get: function () {
  66831. return 2;
  66832. },
  66833. enumerable: true,
  66834. configurable: true
  66835. });
  66836. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66837. get: function () {
  66838. return 3;
  66839. },
  66840. enumerable: true,
  66841. configurable: true
  66842. });
  66843. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66844. get: function () {
  66845. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66846. },
  66847. set: function (value) {
  66848. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66849. },
  66850. enumerable: true,
  66851. configurable: true
  66852. });
  66853. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66854. get: function () {
  66855. return SceneLoader._ShowLoadingScreen;
  66856. },
  66857. set: function (value) {
  66858. SceneLoader._ShowLoadingScreen = value;
  66859. },
  66860. enumerable: true,
  66861. configurable: true
  66862. });
  66863. Object.defineProperty(SceneLoader, "loggingLevel", {
  66864. get: function () {
  66865. return SceneLoader._loggingLevel;
  66866. },
  66867. set: function (value) {
  66868. SceneLoader._loggingLevel = value;
  66869. },
  66870. enumerable: true,
  66871. configurable: true
  66872. });
  66873. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66874. get: function () {
  66875. return SceneLoader._CleanBoneMatrixWeights;
  66876. },
  66877. set: function (value) {
  66878. SceneLoader._CleanBoneMatrixWeights = value;
  66879. },
  66880. enumerable: true,
  66881. configurable: true
  66882. });
  66883. SceneLoader._getDefaultPlugin = function () {
  66884. return SceneLoader._registeredPlugins[".babylon"];
  66885. };
  66886. SceneLoader._getPluginForExtension = function (extension) {
  66887. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66888. if (registeredPlugin) {
  66889. return registeredPlugin;
  66890. }
  66891. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  66892. return SceneLoader._getDefaultPlugin();
  66893. };
  66894. SceneLoader._getPluginForDirectLoad = function (data) {
  66895. for (var extension in SceneLoader._registeredPlugins) {
  66896. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66897. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66898. return SceneLoader._registeredPlugins[extension];
  66899. }
  66900. }
  66901. return SceneLoader._getDefaultPlugin();
  66902. };
  66903. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66904. if (sceneFilename.name) {
  66905. sceneFilename = sceneFilename.name;
  66906. }
  66907. var queryStringPosition = sceneFilename.indexOf("?");
  66908. if (queryStringPosition !== -1) {
  66909. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66910. }
  66911. var dotPosition = sceneFilename.lastIndexOf(".");
  66912. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66913. return SceneLoader._getPluginForExtension(extension);
  66914. };
  66915. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66916. SceneLoader._getDirectLoad = function (sceneFilename) {
  66917. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66918. return sceneFilename.substr(5);
  66919. }
  66920. return null;
  66921. };
  66922. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66923. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66924. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66925. var plugin;
  66926. if (registeredPlugin.plugin.createPlugin) {
  66927. plugin = registeredPlugin.plugin.createPlugin();
  66928. }
  66929. else {
  66930. plugin = registeredPlugin.plugin;
  66931. }
  66932. var useArrayBuffer = registeredPlugin.isBinary;
  66933. var database;
  66934. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66935. var dataCallback = function (data, responseURL) {
  66936. if (scene.isDisposed) {
  66937. onError("Scene has been disposed");
  66938. return;
  66939. }
  66940. scene.database = database;
  66941. onSuccess(plugin, data, responseURL);
  66942. };
  66943. var request = null;
  66944. var pluginDisposed = false;
  66945. var onDisposeObservable = plugin.onDisposeObservable;
  66946. if (onDisposeObservable) {
  66947. onDisposeObservable.add(function () {
  66948. pluginDisposed = true;
  66949. if (request) {
  66950. request.abort();
  66951. request = null;
  66952. }
  66953. onDispose();
  66954. });
  66955. }
  66956. var manifestChecked = function () {
  66957. if (pluginDisposed) {
  66958. return;
  66959. }
  66960. var url = rootUrl + sceneFilename;
  66961. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66962. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66963. } : undefined, database, useArrayBuffer, function (request, exception) {
  66964. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66965. });
  66966. };
  66967. if (directLoad) {
  66968. dataCallback(directLoad);
  66969. return plugin;
  66970. }
  66971. if (rootUrl.indexOf("file:") === -1) {
  66972. var engine = scene.getEngine();
  66973. var canUseOfflineSupport = engine.enableOfflineSupport;
  66974. if (canUseOfflineSupport) {
  66975. // Also check for exceptions
  66976. var exceptionFound = false;
  66977. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66978. var regex = _a[_i];
  66979. if (regex.test(rootUrl + sceneFilename)) {
  66980. exceptionFound = true;
  66981. break;
  66982. }
  66983. }
  66984. canUseOfflineSupport = !exceptionFound;
  66985. }
  66986. if (canUseOfflineSupport) {
  66987. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66988. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  66989. }
  66990. else {
  66991. manifestChecked();
  66992. }
  66993. }
  66994. // Loading file from disk via input file or drag'n'drop
  66995. else {
  66996. var fileOrString = sceneFilename;
  66997. if (fileOrString.name) { // File
  66998. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66999. }
  67000. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67001. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67002. }
  67003. else {
  67004. onError("Unable to find file named " + sceneFilename);
  67005. }
  67006. }
  67007. return plugin;
  67008. };
  67009. // Public functions
  67010. SceneLoader.GetPluginForExtension = function (extension) {
  67011. return SceneLoader._getPluginForExtension(extension).plugin;
  67012. };
  67013. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67014. return !!SceneLoader._registeredPlugins[extension];
  67015. };
  67016. SceneLoader.RegisterPlugin = function (plugin) {
  67017. if (typeof plugin.extensions === "string") {
  67018. var extension = plugin.extensions;
  67019. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67020. plugin: plugin,
  67021. isBinary: false
  67022. };
  67023. }
  67024. else {
  67025. var extensions = plugin.extensions;
  67026. Object.keys(extensions).forEach(function (extension) {
  67027. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67028. plugin: plugin,
  67029. isBinary: extensions[extension].isBinary
  67030. };
  67031. });
  67032. }
  67033. };
  67034. /**
  67035. * Import meshes into a scene
  67036. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67037. * @param rootUrl a string that defines the root url for scene and resources
  67038. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67039. * @param scene the instance of BABYLON.Scene to append to
  67040. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67041. * @param onProgress a callback with a progress event for each file being loaded
  67042. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67043. * @param pluginExtension the extension used to determine the plugin
  67044. * @returns The loaded plugin
  67045. */
  67046. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67047. if (onSuccess === void 0) { onSuccess = null; }
  67048. if (onProgress === void 0) { onProgress = null; }
  67049. if (onError === void 0) { onError = null; }
  67050. if (pluginExtension === void 0) { pluginExtension = null; }
  67051. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67052. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67053. return null;
  67054. }
  67055. var loadingToken = {};
  67056. scene._addPendingData(loadingToken);
  67057. var disposeHandler = function () {
  67058. scene._removePendingData(loadingToken);
  67059. };
  67060. var errorHandler = function (message, exception) {
  67061. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67062. if (onError) {
  67063. onError(scene, errorMessage, exception);
  67064. }
  67065. else {
  67066. BABYLON.Tools.Error(errorMessage);
  67067. // should the exception be thrown?
  67068. }
  67069. disposeHandler();
  67070. };
  67071. var progressHandler = onProgress ? function (event) {
  67072. try {
  67073. onProgress(event);
  67074. }
  67075. catch (e) {
  67076. errorHandler("Error in onProgress callback", e);
  67077. }
  67078. } : undefined;
  67079. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67080. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67081. if (onSuccess) {
  67082. try {
  67083. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67084. }
  67085. catch (e) {
  67086. errorHandler("Error in onSuccess callback", e);
  67087. }
  67088. }
  67089. scene._removePendingData(loadingToken);
  67090. };
  67091. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67092. if (plugin.rewriteRootURL) {
  67093. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67094. }
  67095. if (sceneFilename === "") {
  67096. if (sceneFilename === "") {
  67097. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67098. }
  67099. }
  67100. if (plugin.importMesh) {
  67101. var syncedPlugin = plugin;
  67102. var meshes = new Array();
  67103. var particleSystems = new Array();
  67104. var skeletons = new Array();
  67105. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67106. return;
  67107. }
  67108. scene.loadingPluginName = plugin.name;
  67109. successHandler(meshes, particleSystems, skeletons, []);
  67110. }
  67111. else {
  67112. var asyncedPlugin = plugin;
  67113. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67114. scene.loadingPluginName = plugin.name;
  67115. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67116. }).catch(function (error) {
  67117. errorHandler(error.message, error);
  67118. });
  67119. }
  67120. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67121. };
  67122. /**
  67123. * Import meshes into a scene
  67124. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67125. * @param rootUrl a string that defines the root url for scene and resources
  67126. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67127. * @param scene the instance of BABYLON.Scene to append to
  67128. * @param onProgress a callback with a progress event for each file being loaded
  67129. * @param pluginExtension the extension used to determine the plugin
  67130. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67131. */
  67132. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67133. if (onProgress === void 0) { onProgress = null; }
  67134. if (pluginExtension === void 0) { pluginExtension = null; }
  67135. return new Promise(function (resolve, reject) {
  67136. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67137. resolve({
  67138. meshes: meshes,
  67139. particleSystems: particleSystems,
  67140. skeletons: skeletons,
  67141. animationGroups: animationGroups
  67142. });
  67143. }, onProgress, function (scene, message, exception) {
  67144. reject(exception || new Error(message));
  67145. }, pluginExtension);
  67146. });
  67147. };
  67148. /**
  67149. * Load a scene
  67150. * @param rootUrl a string that defines the root url for scene and resources
  67151. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67152. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67153. * @param onSuccess a callback with the scene when import succeeds
  67154. * @param onProgress a callback with a progress event for each file being loaded
  67155. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67156. * @param pluginExtension the extension used to determine the plugin
  67157. * @returns The loaded plugin
  67158. */
  67159. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67160. if (onSuccess === void 0) { onSuccess = null; }
  67161. if (onProgress === void 0) { onProgress = null; }
  67162. if (onError === void 0) { onError = null; }
  67163. if (pluginExtension === void 0) { pluginExtension = null; }
  67164. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67165. };
  67166. /**
  67167. * Load a scene
  67168. * @param rootUrl a string that defines the root url for scene and resources
  67169. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67170. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67171. * @param onProgress a callback with a progress event for each file being loaded
  67172. * @param pluginExtension the extension used to determine the plugin
  67173. * @returns The loaded scene
  67174. */
  67175. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67176. if (onProgress === void 0) { onProgress = null; }
  67177. if (pluginExtension === void 0) { pluginExtension = null; }
  67178. return new Promise(function (resolve, reject) {
  67179. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67180. resolve(scene);
  67181. }, onProgress, function (scene, message, exception) {
  67182. reject(exception || new Error(message));
  67183. }, pluginExtension);
  67184. });
  67185. };
  67186. /**
  67187. * Append a scene
  67188. * @param rootUrl a string that defines the root url for scene and resources
  67189. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67190. * @param scene is the instance of BABYLON.Scene to append to
  67191. * @param onSuccess a callback with the scene when import succeeds
  67192. * @param onProgress a callback with a progress event for each file being loaded
  67193. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67194. * @param pluginExtension the extension used to determine the plugin
  67195. * @returns The loaded plugin
  67196. */
  67197. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67198. if (onSuccess === void 0) { onSuccess = null; }
  67199. if (onProgress === void 0) { onProgress = null; }
  67200. if (onError === void 0) { onError = null; }
  67201. if (pluginExtension === void 0) { pluginExtension = null; }
  67202. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67203. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67204. return null;
  67205. }
  67206. if (SceneLoader.ShowLoadingScreen) {
  67207. scene.getEngine().displayLoadingUI();
  67208. }
  67209. var loadingToken = {};
  67210. scene._addPendingData(loadingToken);
  67211. var disposeHandler = function () {
  67212. scene._removePendingData(loadingToken);
  67213. scene.getEngine().hideLoadingUI();
  67214. };
  67215. var errorHandler = function (message, exception) {
  67216. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67217. if (onError) {
  67218. onError(scene, errorMessage, exception);
  67219. }
  67220. else {
  67221. BABYLON.Tools.Error(errorMessage);
  67222. // should the exception be thrown?
  67223. }
  67224. disposeHandler();
  67225. };
  67226. var progressHandler = onProgress ? function (event) {
  67227. try {
  67228. onProgress(event);
  67229. }
  67230. catch (e) {
  67231. errorHandler("Error in onProgress callback", e);
  67232. }
  67233. } : undefined;
  67234. var successHandler = function () {
  67235. if (onSuccess) {
  67236. try {
  67237. onSuccess(scene);
  67238. }
  67239. catch (e) {
  67240. errorHandler("Error in onSuccess callback", e);
  67241. }
  67242. }
  67243. scene._removePendingData(loadingToken);
  67244. };
  67245. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67246. if (sceneFilename === "") {
  67247. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67248. }
  67249. if (plugin.load) {
  67250. var syncedPlugin = plugin;
  67251. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67252. return;
  67253. }
  67254. scene.loadingPluginName = plugin.name;
  67255. successHandler();
  67256. }
  67257. else {
  67258. var asyncedPlugin = plugin;
  67259. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67260. scene.loadingPluginName = plugin.name;
  67261. successHandler();
  67262. }).catch(function (error) {
  67263. errorHandler(error.message, error);
  67264. });
  67265. }
  67266. if (SceneLoader.ShowLoadingScreen) {
  67267. scene.executeWhenReady(function () {
  67268. scene.getEngine().hideLoadingUI();
  67269. });
  67270. }
  67271. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67272. };
  67273. /**
  67274. * Append a scene
  67275. * @param rootUrl a string that defines the root url for scene and resources
  67276. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67277. * @param scene is the instance of BABYLON.Scene to append to
  67278. * @param onProgress a callback with a progress event for each file being loaded
  67279. * @param pluginExtension the extension used to determine the plugin
  67280. * @returns The given scene
  67281. */
  67282. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67283. if (onProgress === void 0) { onProgress = null; }
  67284. if (pluginExtension === void 0) { pluginExtension = null; }
  67285. return new Promise(function (resolve, reject) {
  67286. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67287. resolve(scene);
  67288. }, onProgress, function (scene, message, exception) {
  67289. reject(exception || new Error(message));
  67290. }, pluginExtension);
  67291. });
  67292. };
  67293. /**
  67294. * Load a scene into an asset container
  67295. * @param rootUrl a string that defines the root url for scene and resources
  67296. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67297. * @param scene is the instance of BABYLON.Scene to append to
  67298. * @param onSuccess a callback with the scene when import succeeds
  67299. * @param onProgress a callback with a progress event for each file being loaded
  67300. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67301. * @param pluginExtension the extension used to determine the plugin
  67302. * @returns The loaded plugin
  67303. */
  67304. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67305. if (onSuccess === void 0) { onSuccess = null; }
  67306. if (onProgress === void 0) { onProgress = null; }
  67307. if (onError === void 0) { onError = null; }
  67308. if (pluginExtension === void 0) { pluginExtension = null; }
  67309. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67310. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67311. return null;
  67312. }
  67313. var loadingToken = {};
  67314. scene._addPendingData(loadingToken);
  67315. var disposeHandler = function () {
  67316. scene._removePendingData(loadingToken);
  67317. };
  67318. var errorHandler = function (message, exception) {
  67319. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67320. if (onError) {
  67321. onError(scene, errorMessage, exception);
  67322. }
  67323. else {
  67324. BABYLON.Tools.Error(errorMessage);
  67325. // should the exception be thrown?
  67326. }
  67327. disposeHandler();
  67328. };
  67329. var progressHandler = onProgress ? function (event) {
  67330. try {
  67331. onProgress(event);
  67332. }
  67333. catch (e) {
  67334. errorHandler("Error in onProgress callback", e);
  67335. }
  67336. } : undefined;
  67337. var successHandler = function (assets) {
  67338. if (onSuccess) {
  67339. try {
  67340. onSuccess(assets);
  67341. }
  67342. catch (e) {
  67343. errorHandler("Error in onSuccess callback", e);
  67344. }
  67345. }
  67346. scene._removePendingData(loadingToken);
  67347. };
  67348. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67349. if (plugin.loadAssetContainer) {
  67350. var syncedPlugin = plugin;
  67351. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67352. if (!assetContainer) {
  67353. return;
  67354. }
  67355. scene.loadingPluginName = plugin.name;
  67356. successHandler(assetContainer);
  67357. }
  67358. else if (plugin.loadAssetContainerAsync) {
  67359. var asyncedPlugin = plugin;
  67360. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67361. scene.loadingPluginName = plugin.name;
  67362. successHandler(assetContainer);
  67363. }).catch(function (error) {
  67364. errorHandler(error.message, error);
  67365. });
  67366. }
  67367. else {
  67368. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67369. }
  67370. if (SceneLoader.ShowLoadingScreen) {
  67371. scene.executeWhenReady(function () {
  67372. scene.getEngine().hideLoadingUI();
  67373. });
  67374. }
  67375. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67376. };
  67377. /**
  67378. * Load a scene into an asset container
  67379. * @param rootUrl a string that defines the root url for scene and resources
  67380. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67381. * @param scene is the instance of BABYLON.Scene to append to
  67382. * @param onProgress a callback with a progress event for each file being loaded
  67383. * @param pluginExtension the extension used to determine the plugin
  67384. * @returns The loaded asset container
  67385. */
  67386. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67387. if (onProgress === void 0) { onProgress = null; }
  67388. if (pluginExtension === void 0) { pluginExtension = null; }
  67389. return new Promise(function (resolve, reject) {
  67390. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67391. resolve(assetContainer);
  67392. }, onProgress, function (scene, message, exception) {
  67393. reject(exception || new Error(message));
  67394. }, pluginExtension);
  67395. });
  67396. };
  67397. // Flags
  67398. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67399. SceneLoader._ShowLoadingScreen = true;
  67400. SceneLoader._CleanBoneMatrixWeights = false;
  67401. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67402. // Members
  67403. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67404. SceneLoader._registeredPlugins = {};
  67405. return SceneLoader;
  67406. }());
  67407. BABYLON.SceneLoader = SceneLoader;
  67408. ;
  67409. })(BABYLON || (BABYLON = {}));
  67410. //# sourceMappingURL=babylon.sceneLoader.js.map
  67411. var BABYLON;
  67412. (function (BABYLON) {
  67413. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67414. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67415. var parsedMaterial = parsedData.materials[index];
  67416. if (parsedMaterial.id === id) {
  67417. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67418. }
  67419. }
  67420. return null;
  67421. };
  67422. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67423. for (var i in names) {
  67424. if (mesh.name === names[i]) {
  67425. hierarchyIds.push(mesh.id);
  67426. return true;
  67427. }
  67428. }
  67429. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67430. hierarchyIds.push(mesh.id);
  67431. return true;
  67432. }
  67433. return false;
  67434. };
  67435. var logOperation = function (operation, producer) {
  67436. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67437. };
  67438. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67439. if (addToScene === void 0) { addToScene = false; }
  67440. var container = new BABYLON.AssetContainer(scene);
  67441. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67442. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67443. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67444. // and avoid problems with multiple concurrent .babylon loads.
  67445. var log = "importScene has failed JSON parse";
  67446. try {
  67447. var parsedData = JSON.parse(data);
  67448. log = "";
  67449. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67450. var index;
  67451. var cache;
  67452. // Lights
  67453. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67454. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67455. var parsedLight = parsedData.lights[index];
  67456. var light = BABYLON.Light.Parse(parsedLight, scene);
  67457. if (light) {
  67458. container.lights.push(light);
  67459. log += (index === 0 ? "\n\tLights:" : "");
  67460. log += "\n\t\t" + light.toString(fullDetails);
  67461. }
  67462. }
  67463. }
  67464. // Animations
  67465. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67466. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67467. var parsedAnimation = parsedData.animations[index];
  67468. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67469. scene.animations.push(animation);
  67470. container.animations.push(animation);
  67471. log += (index === 0 ? "\n\tAnimations:" : "");
  67472. log += "\n\t\t" + animation.toString(fullDetails);
  67473. }
  67474. }
  67475. // Materials
  67476. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67477. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67478. var parsedMaterial = parsedData.materials[index];
  67479. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67480. container.materials.push(mat);
  67481. log += (index === 0 ? "\n\tMaterials:" : "");
  67482. log += "\n\t\t" + mat.toString(fullDetails);
  67483. }
  67484. }
  67485. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67486. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67487. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67488. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67489. container.multiMaterials.push(mmat);
  67490. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67491. log += "\n\t\t" + mmat.toString(fullDetails);
  67492. }
  67493. }
  67494. // Morph targets
  67495. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67496. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67497. var managerData = _a[_i];
  67498. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67499. }
  67500. }
  67501. // Skeletons
  67502. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67503. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67504. var parsedSkeleton = parsedData.skeletons[index];
  67505. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67506. container.skeletons.push(skeleton);
  67507. log += (index === 0 ? "\n\tSkeletons:" : "");
  67508. log += "\n\t\t" + skeleton.toString(fullDetails);
  67509. }
  67510. }
  67511. // Geometries
  67512. var geometries = parsedData.geometries;
  67513. if (geometries !== undefined && geometries !== null) {
  67514. var addedGeometry = new Array();
  67515. // Boxes
  67516. var boxes = geometries.boxes;
  67517. if (boxes !== undefined && boxes !== null) {
  67518. for (index = 0, cache = boxes.length; index < cache; index++) {
  67519. var parsedBox = boxes[index];
  67520. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67521. }
  67522. }
  67523. // Spheres
  67524. var spheres = geometries.spheres;
  67525. if (spheres !== undefined && spheres !== null) {
  67526. for (index = 0, cache = spheres.length; index < cache; index++) {
  67527. var parsedSphere = spheres[index];
  67528. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67529. }
  67530. }
  67531. // Cylinders
  67532. var cylinders = geometries.cylinders;
  67533. if (cylinders !== undefined && cylinders !== null) {
  67534. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67535. var parsedCylinder = cylinders[index];
  67536. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67537. }
  67538. }
  67539. // Toruses
  67540. var toruses = geometries.toruses;
  67541. if (toruses !== undefined && toruses !== null) {
  67542. for (index = 0, cache = toruses.length; index < cache; index++) {
  67543. var parsedTorus = toruses[index];
  67544. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67545. }
  67546. }
  67547. // Grounds
  67548. var grounds = geometries.grounds;
  67549. if (grounds !== undefined && grounds !== null) {
  67550. for (index = 0, cache = grounds.length; index < cache; index++) {
  67551. var parsedGround = grounds[index];
  67552. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67553. }
  67554. }
  67555. // Planes
  67556. var planes = geometries.planes;
  67557. if (planes !== undefined && planes !== null) {
  67558. for (index = 0, cache = planes.length; index < cache; index++) {
  67559. var parsedPlane = planes[index];
  67560. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67561. }
  67562. }
  67563. // TorusKnots
  67564. var torusKnots = geometries.torusKnots;
  67565. if (torusKnots !== undefined && torusKnots !== null) {
  67566. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67567. var parsedTorusKnot = torusKnots[index];
  67568. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67569. }
  67570. }
  67571. // VertexData
  67572. var vertexData = geometries.vertexData;
  67573. if (vertexData !== undefined && vertexData !== null) {
  67574. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67575. var parsedVertexData = vertexData[index];
  67576. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67577. }
  67578. }
  67579. addedGeometry.forEach(function (g) {
  67580. if (g) {
  67581. container.geometries.push(g);
  67582. }
  67583. });
  67584. }
  67585. // Transform nodes
  67586. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67587. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67588. var parsedTransformNode = parsedData.transformNodes[index];
  67589. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67590. container.transformNodes.push(node);
  67591. }
  67592. }
  67593. // Meshes
  67594. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67595. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67596. var parsedMesh = parsedData.meshes[index];
  67597. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67598. container.meshes.push(mesh);
  67599. log += (index === 0 ? "\n\tMeshes:" : "");
  67600. log += "\n\t\t" + mesh.toString(fullDetails);
  67601. }
  67602. }
  67603. // Cameras
  67604. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67605. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67606. var parsedCamera = parsedData.cameras[index];
  67607. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67608. container.cameras.push(camera);
  67609. log += (index === 0 ? "\n\tCameras:" : "");
  67610. log += "\n\t\t" + camera.toString(fullDetails);
  67611. }
  67612. }
  67613. // Browsing all the graph to connect the dots
  67614. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67615. var camera = scene.cameras[index];
  67616. if (camera._waitingParentId) {
  67617. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67618. camera._waitingParentId = null;
  67619. }
  67620. }
  67621. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67622. var light_1 = scene.lights[index];
  67623. if (light_1 && light_1._waitingParentId) {
  67624. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67625. light_1._waitingParentId = null;
  67626. }
  67627. }
  67628. // Sounds
  67629. // TODO: add sound
  67630. var loadedSounds = [];
  67631. var loadedSound;
  67632. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67633. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67634. var parsedSound = parsedData.sounds[index];
  67635. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67636. if (!parsedSound.url)
  67637. parsedSound.url = parsedSound.name;
  67638. if (!loadedSounds[parsedSound.url]) {
  67639. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67640. loadedSounds[parsedSound.url] = loadedSound;
  67641. container.sounds.push(loadedSound);
  67642. }
  67643. else {
  67644. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67645. }
  67646. }
  67647. else {
  67648. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67649. }
  67650. }
  67651. }
  67652. loadedSounds = [];
  67653. // Connect parents & children and parse actions
  67654. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67655. var transformNode = scene.transformNodes[index];
  67656. if (transformNode._waitingParentId) {
  67657. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67658. transformNode._waitingParentId = null;
  67659. }
  67660. }
  67661. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67662. var mesh = scene.meshes[index];
  67663. if (mesh._waitingParentId) {
  67664. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67665. mesh._waitingParentId = null;
  67666. }
  67667. if (mesh._waitingActions) {
  67668. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67669. mesh._waitingActions = null;
  67670. }
  67671. }
  67672. // freeze world matrix application
  67673. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67674. var currentMesh = scene.meshes[index];
  67675. if (currentMesh._waitingFreezeWorldMatrix) {
  67676. currentMesh.freezeWorldMatrix();
  67677. currentMesh._waitingFreezeWorldMatrix = null;
  67678. }
  67679. else {
  67680. currentMesh.computeWorldMatrix(true);
  67681. }
  67682. }
  67683. // Particles Systems
  67684. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67685. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67686. var parsedParticleSystem = parsedData.particleSystems[index];
  67687. if (parsedParticleSystem.activeParticleCount) {
  67688. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67689. container.particleSystems.push(ps);
  67690. }
  67691. else {
  67692. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67693. container.particleSystems.push(ps);
  67694. }
  67695. }
  67696. }
  67697. // Lens flares
  67698. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67699. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67700. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67701. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67702. container.lensFlareSystems.push(lf);
  67703. }
  67704. }
  67705. // Shadows
  67706. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67707. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67708. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67709. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67710. container.shadowGenerators.push(sg);
  67711. }
  67712. }
  67713. // Lights exclusions / inclusions
  67714. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67715. var light_2 = scene.lights[index];
  67716. // Excluded check
  67717. if (light_2._excludedMeshesIds.length > 0) {
  67718. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67719. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67720. if (excludedMesh) {
  67721. light_2.excludedMeshes.push(excludedMesh);
  67722. }
  67723. }
  67724. light_2._excludedMeshesIds = [];
  67725. }
  67726. // Included check
  67727. if (light_2._includedOnlyMeshesIds.length > 0) {
  67728. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67729. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67730. if (includedOnlyMesh) {
  67731. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67732. }
  67733. }
  67734. light_2._includedOnlyMeshesIds = [];
  67735. }
  67736. }
  67737. // Effect layers
  67738. if (parsedData.effectLayers) {
  67739. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67740. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67741. container.effectLayers.push(effectLayer);
  67742. }
  67743. }
  67744. // Actions (scene)
  67745. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67746. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67747. }
  67748. if (!addToScene) {
  67749. container.removeAllFromScene();
  67750. }
  67751. }
  67752. catch (err) {
  67753. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67754. if (onError) {
  67755. onError(msg, err);
  67756. }
  67757. else {
  67758. BABYLON.Tools.Log(msg);
  67759. throw err;
  67760. }
  67761. }
  67762. finally {
  67763. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67764. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67765. }
  67766. }
  67767. return container;
  67768. };
  67769. BABYLON.SceneLoader.RegisterPlugin({
  67770. name: "babylon.js",
  67771. extensions: ".babylon",
  67772. canDirectLoad: function (data) {
  67773. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67774. return true;
  67775. }
  67776. return false;
  67777. },
  67778. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67779. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67780. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67781. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67782. // and avoid problems with multiple concurrent .babylon loads.
  67783. var log = "importMesh has failed JSON parse";
  67784. try {
  67785. var parsedData = JSON.parse(data);
  67786. log = "";
  67787. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67788. if (!meshesNames) {
  67789. meshesNames = null;
  67790. }
  67791. else if (!Array.isArray(meshesNames)) {
  67792. meshesNames = [meshesNames];
  67793. }
  67794. var hierarchyIds = new Array();
  67795. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67796. var loadedSkeletonsIds = [];
  67797. var loadedMaterialsIds = [];
  67798. var index;
  67799. var cache;
  67800. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67801. var parsedMesh = parsedData.meshes[index];
  67802. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67803. if (meshesNames !== null) {
  67804. // Remove found mesh name from list.
  67805. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67806. }
  67807. //Geometry?
  67808. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67809. //does the file contain geometries?
  67810. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67811. //find the correct geometry and add it to the scene
  67812. var found = false;
  67813. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67814. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67815. return;
  67816. }
  67817. else {
  67818. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67819. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67820. switch (geometryType) {
  67821. case "boxes":
  67822. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67823. break;
  67824. case "spheres":
  67825. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67826. break;
  67827. case "cylinders":
  67828. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67829. break;
  67830. case "toruses":
  67831. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67832. break;
  67833. case "grounds":
  67834. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67835. break;
  67836. case "planes":
  67837. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67838. break;
  67839. case "torusKnots":
  67840. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67841. break;
  67842. case "vertexData":
  67843. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67844. break;
  67845. }
  67846. found = true;
  67847. }
  67848. });
  67849. }
  67850. });
  67851. if (found === false) {
  67852. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67853. }
  67854. }
  67855. }
  67856. // Material ?
  67857. if (parsedMesh.materialId) {
  67858. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67859. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67860. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67861. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67862. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67863. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67864. var subMatId = parsedMultiMaterial.materials[matIndex];
  67865. loadedMaterialsIds.push(subMatId);
  67866. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67867. if (mat) {
  67868. log += "\n\tMaterial " + mat.toString(fullDetails);
  67869. }
  67870. }
  67871. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67872. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67873. if (mmat) {
  67874. materialFound = true;
  67875. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67876. }
  67877. break;
  67878. }
  67879. }
  67880. }
  67881. if (materialFound === false) {
  67882. loadedMaterialsIds.push(parsedMesh.materialId);
  67883. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67884. if (!mat) {
  67885. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67886. }
  67887. else {
  67888. log += "\n\tMaterial " + mat.toString(fullDetails);
  67889. }
  67890. }
  67891. }
  67892. // Skeleton ?
  67893. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67894. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67895. if (skeletonAlreadyLoaded === false) {
  67896. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67897. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67898. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67899. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67900. skeletons.push(skeleton);
  67901. loadedSkeletonsIds.push(parsedSkeleton.id);
  67902. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67903. }
  67904. }
  67905. }
  67906. }
  67907. // Morph targets ?
  67908. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67909. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67910. var managerData = _a[_i];
  67911. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67912. }
  67913. }
  67914. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67915. meshes.push(mesh);
  67916. log += "\n\tMesh " + mesh.toString(fullDetails);
  67917. }
  67918. }
  67919. // Connecting parents
  67920. var currentMesh;
  67921. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67922. currentMesh = scene.meshes[index];
  67923. if (currentMesh._waitingParentId) {
  67924. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67925. currentMesh._waitingParentId = null;
  67926. }
  67927. }
  67928. // freeze and compute world matrix application
  67929. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67930. currentMesh = scene.meshes[index];
  67931. if (currentMesh._waitingFreezeWorldMatrix) {
  67932. currentMesh.freezeWorldMatrix();
  67933. currentMesh._waitingFreezeWorldMatrix = null;
  67934. }
  67935. else {
  67936. currentMesh.computeWorldMatrix(true);
  67937. }
  67938. }
  67939. }
  67940. // Particles
  67941. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67942. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67943. var parsedParticleSystem = parsedData.particleSystems[index];
  67944. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67945. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67946. }
  67947. }
  67948. }
  67949. return true;
  67950. }
  67951. catch (err) {
  67952. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67953. if (onError) {
  67954. onError(msg, err);
  67955. }
  67956. else {
  67957. BABYLON.Tools.Log(msg);
  67958. throw err;
  67959. }
  67960. }
  67961. finally {
  67962. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67963. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67964. }
  67965. }
  67966. return false;
  67967. },
  67968. load: function (scene, data, rootUrl, onError) {
  67969. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67970. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67971. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67972. // and avoid problems with multiple concurrent .babylon loads.
  67973. var log = "importScene has failed JSON parse";
  67974. try {
  67975. var parsedData = JSON.parse(data);
  67976. log = "";
  67977. // Scene
  67978. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67979. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67980. }
  67981. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67982. scene.autoClear = parsedData.autoClear;
  67983. }
  67984. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67985. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67986. }
  67987. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67988. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67989. }
  67990. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67991. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67992. }
  67993. // Fog
  67994. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67995. scene.fogMode = parsedData.fogMode;
  67996. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67997. scene.fogStart = parsedData.fogStart;
  67998. scene.fogEnd = parsedData.fogEnd;
  67999. scene.fogDensity = parsedData.fogDensity;
  68000. log += "\tFog mode for scene: ";
  68001. switch (scene.fogMode) {
  68002. // getters not compiling, so using hardcoded
  68003. case 1:
  68004. log += "exp\n";
  68005. break;
  68006. case 2:
  68007. log += "exp2\n";
  68008. break;
  68009. case 3:
  68010. log += "linear\n";
  68011. break;
  68012. }
  68013. }
  68014. //Physics
  68015. if (parsedData.physicsEnabled) {
  68016. var physicsPlugin;
  68017. if (parsedData.physicsEngine === "cannon") {
  68018. physicsPlugin = new BABYLON.CannonJSPlugin();
  68019. }
  68020. else if (parsedData.physicsEngine === "oimo") {
  68021. physicsPlugin = new BABYLON.OimoJSPlugin();
  68022. }
  68023. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68024. //else - default engine, which is currently oimo
  68025. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68026. scene.enablePhysics(physicsGravity, physicsPlugin);
  68027. }
  68028. // Metadata
  68029. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68030. scene.metadata = parsedData.metadata;
  68031. }
  68032. //collisions, if defined. otherwise, default is true
  68033. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68034. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68035. }
  68036. scene.workerCollisions = !!parsedData.workerCollisions;
  68037. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68038. if (!container) {
  68039. return false;
  68040. }
  68041. if (parsedData.autoAnimate) {
  68042. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68043. }
  68044. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68045. scene.setActiveCameraByID(parsedData.activeCameraID);
  68046. }
  68047. // Environment texture
  68048. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68049. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68050. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68051. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68052. if (parsedData.environmentTextureRotationY) {
  68053. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68054. }
  68055. scene.environmentTexture = hdrTexture;
  68056. }
  68057. else {
  68058. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68059. if (parsedData.environmentTextureRotationY) {
  68060. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68061. }
  68062. scene.environmentTexture = cubeTexture;
  68063. }
  68064. if (parsedData.createDefaultSkybox === true) {
  68065. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68066. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68067. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68068. }
  68069. }
  68070. // Finish
  68071. return true;
  68072. }
  68073. catch (err) {
  68074. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68075. if (onError) {
  68076. onError(msg, err);
  68077. }
  68078. else {
  68079. BABYLON.Tools.Log(msg);
  68080. throw err;
  68081. }
  68082. }
  68083. finally {
  68084. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68085. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68086. }
  68087. }
  68088. return false;
  68089. },
  68090. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68091. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68092. return container;
  68093. }
  68094. });
  68095. })(BABYLON || (BABYLON = {}));
  68096. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68097. var BABYLON;
  68098. (function (BABYLON) {
  68099. var FilesInput = /** @class */ (function () {
  68100. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68101. this.onProcessFileCallback = function () { return true; };
  68102. this._engine = engine;
  68103. this._currentScene = scene;
  68104. this._sceneLoadedCallback = sceneLoadedCallback;
  68105. this._progressCallback = progressCallback;
  68106. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68107. this._textureLoadingCallback = textureLoadingCallback;
  68108. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68109. this._onReloadCallback = onReloadCallback;
  68110. this._errorCallback = errorCallback;
  68111. }
  68112. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68113. var _this = this;
  68114. if (elementToMonitor) {
  68115. this._elementToMonitor = elementToMonitor;
  68116. this._dragEnterHandler = function (e) { _this.drag(e); };
  68117. this._dragOverHandler = function (e) { _this.drag(e); };
  68118. this._dropHandler = function (e) { _this.drop(e); };
  68119. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68120. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68121. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68122. }
  68123. };
  68124. FilesInput.prototype.dispose = function () {
  68125. if (!this._elementToMonitor) {
  68126. return;
  68127. }
  68128. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68129. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68130. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68131. };
  68132. FilesInput.prototype.renderFunction = function () {
  68133. if (this._additionalRenderLoopLogicCallback) {
  68134. this._additionalRenderLoopLogicCallback();
  68135. }
  68136. if (this._currentScene) {
  68137. if (this._textureLoadingCallback) {
  68138. var remaining = this._currentScene.getWaitingItemsCount();
  68139. if (remaining > 0) {
  68140. this._textureLoadingCallback(remaining);
  68141. }
  68142. }
  68143. this._currentScene.render();
  68144. }
  68145. };
  68146. FilesInput.prototype.drag = function (e) {
  68147. e.stopPropagation();
  68148. e.preventDefault();
  68149. };
  68150. FilesInput.prototype.drop = function (eventDrop) {
  68151. eventDrop.stopPropagation();
  68152. eventDrop.preventDefault();
  68153. this.loadFiles(eventDrop);
  68154. };
  68155. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68156. var _this = this;
  68157. var reader = folder.createReader();
  68158. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68159. reader.readEntries(function (entries) {
  68160. remaining.count += entries.length;
  68161. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68162. var entry = entries_1[_i];
  68163. if (entry.isFile) {
  68164. entry.file(function (file) {
  68165. file.correctName = relativePath + file.name;
  68166. files.push(file);
  68167. if (--remaining.count === 0) {
  68168. callback();
  68169. }
  68170. });
  68171. }
  68172. else if (entry.isDirectory) {
  68173. _this._traverseFolder(entry, files, remaining, callback);
  68174. }
  68175. }
  68176. if (--remaining.count) {
  68177. callback();
  68178. }
  68179. });
  68180. };
  68181. FilesInput.prototype._processFiles = function (files) {
  68182. for (var i = 0; i < files.length; i++) {
  68183. var name = files[i].correctName.toLowerCase();
  68184. var extension = name.split('.').pop();
  68185. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68186. continue;
  68187. }
  68188. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68189. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68190. this._sceneFileToLoad = files[i];
  68191. }
  68192. else {
  68193. FilesInput.FilesToLoad[name] = files[i];
  68194. }
  68195. }
  68196. };
  68197. FilesInput.prototype.loadFiles = function (event) {
  68198. var _this = this;
  68199. if (this._startingProcessingFilesCallback)
  68200. this._startingProcessingFilesCallback();
  68201. // Handling data transfer via drag'n'drop
  68202. if (event && event.dataTransfer && event.dataTransfer.files) {
  68203. this._filesToLoad = event.dataTransfer.files;
  68204. }
  68205. // Handling files from input files
  68206. if (event && event.target && event.target.files) {
  68207. this._filesToLoad = event.target.files;
  68208. }
  68209. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68210. var files_1 = new Array();
  68211. var folders = [];
  68212. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68213. for (var i = 0; i < this._filesToLoad.length; i++) {
  68214. var fileToLoad = this._filesToLoad[i];
  68215. var name_1 = fileToLoad.name.toLowerCase();
  68216. var entry = void 0;
  68217. fileToLoad.correctName = name_1;
  68218. if (items) {
  68219. var item = items[i];
  68220. if (item.getAsEntry) {
  68221. entry = item.getAsEntry();
  68222. }
  68223. else if (item.webkitGetAsEntry) {
  68224. entry = item.webkitGetAsEntry();
  68225. }
  68226. }
  68227. if (!entry) {
  68228. files_1.push(fileToLoad);
  68229. }
  68230. else {
  68231. if (entry.isDirectory) {
  68232. folders.push(entry);
  68233. }
  68234. else {
  68235. files_1.push(fileToLoad);
  68236. }
  68237. }
  68238. }
  68239. if (folders.length === 0) {
  68240. this._processFiles(files_1);
  68241. this._processReload();
  68242. }
  68243. else {
  68244. var remaining = { count: folders.length };
  68245. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68246. var folder = folders_1[_i];
  68247. this._traverseFolder(folder, files_1, remaining, function () {
  68248. _this._processFiles(files_1);
  68249. if (remaining.count === 0) {
  68250. _this._processReload();
  68251. }
  68252. });
  68253. }
  68254. }
  68255. }
  68256. };
  68257. FilesInput.prototype._processReload = function () {
  68258. if (this._onReloadCallback) {
  68259. this._onReloadCallback(this._sceneFileToLoad);
  68260. }
  68261. else {
  68262. this.reload();
  68263. }
  68264. };
  68265. FilesInput.prototype.reload = function () {
  68266. var _this = this;
  68267. // If a scene file has been provided
  68268. if (this._sceneFileToLoad) {
  68269. if (this._currentScene) {
  68270. if (BABYLON.Tools.errorsCount > 0) {
  68271. BABYLON.Tools.ClearLogCache();
  68272. }
  68273. this._engine.stopRenderLoop();
  68274. this._currentScene.dispose();
  68275. }
  68276. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68277. if (_this._progressCallback) {
  68278. _this._progressCallback(progress);
  68279. }
  68280. }).then(function (scene) {
  68281. _this._currentScene = scene;
  68282. if (_this._sceneLoadedCallback) {
  68283. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68284. }
  68285. // Wait for textures and shaders to be ready
  68286. _this._currentScene.executeWhenReady(function () {
  68287. _this._engine.runRenderLoop(function () {
  68288. _this.renderFunction();
  68289. });
  68290. });
  68291. }).catch(function (error) {
  68292. if (_this._errorCallback) {
  68293. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68294. }
  68295. });
  68296. }
  68297. else {
  68298. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68299. }
  68300. };
  68301. FilesInput.FilesToLoad = {};
  68302. return FilesInput;
  68303. }());
  68304. BABYLON.FilesInput = FilesInput;
  68305. })(BABYLON || (BABYLON = {}));
  68306. //# sourceMappingURL=babylon.filesInput.js.map
  68307. var BABYLON;
  68308. (function (BABYLON) {
  68309. /**
  68310. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68311. * The underlying implementation relies on an associative array to ensure the best performances.
  68312. * The value can be anything including 'null' but except 'undefined'
  68313. */
  68314. var StringDictionary = /** @class */ (function () {
  68315. function StringDictionary() {
  68316. this._count = 0;
  68317. this._data = {};
  68318. }
  68319. /**
  68320. * This will clear this dictionary and copy the content from the 'source' one.
  68321. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68322. * @param source the dictionary to take the content from and copy to this dictionary
  68323. */
  68324. StringDictionary.prototype.copyFrom = function (source) {
  68325. var _this = this;
  68326. this.clear();
  68327. source.forEach(function (t, v) { return _this.add(t, v); });
  68328. };
  68329. /**
  68330. * Get a value based from its key
  68331. * @param key the given key to get the matching value from
  68332. * @return the value if found, otherwise undefined is returned
  68333. */
  68334. StringDictionary.prototype.get = function (key) {
  68335. var val = this._data[key];
  68336. if (val !== undefined) {
  68337. return val;
  68338. }
  68339. return undefined;
  68340. };
  68341. /**
  68342. * Get a value from its key or add it if it doesn't exist.
  68343. * This method will ensure you that a given key/data will be present in the dictionary.
  68344. * @param key the given key to get the matching value from
  68345. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68346. * The factory will only be invoked if there's no data for the given key.
  68347. * @return the value corresponding to the key.
  68348. */
  68349. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68350. var val = this.get(key);
  68351. if (val !== undefined) {
  68352. return val;
  68353. }
  68354. val = factory(key);
  68355. if (val) {
  68356. this.add(key, val);
  68357. }
  68358. return val;
  68359. };
  68360. /**
  68361. * Get a value from its key if present in the dictionary otherwise add it
  68362. * @param key the key to get the value from
  68363. * @param val if there's no such key/value pair in the dictionary add it with this value
  68364. * @return the value corresponding to the key
  68365. */
  68366. StringDictionary.prototype.getOrAdd = function (key, val) {
  68367. var curVal = this.get(key);
  68368. if (curVal !== undefined) {
  68369. return curVal;
  68370. }
  68371. this.add(key, val);
  68372. return val;
  68373. };
  68374. /**
  68375. * Check if there's a given key in the dictionary
  68376. * @param key the key to check for
  68377. * @return true if the key is present, false otherwise
  68378. */
  68379. StringDictionary.prototype.contains = function (key) {
  68380. return this._data[key] !== undefined;
  68381. };
  68382. /**
  68383. * Add a new key and its corresponding value
  68384. * @param key the key to add
  68385. * @param value the value corresponding to the key
  68386. * @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
  68387. */
  68388. StringDictionary.prototype.add = function (key, value) {
  68389. if (this._data[key] !== undefined) {
  68390. return false;
  68391. }
  68392. this._data[key] = value;
  68393. ++this._count;
  68394. return true;
  68395. };
  68396. StringDictionary.prototype.set = function (key, value) {
  68397. if (this._data[key] === undefined) {
  68398. return false;
  68399. }
  68400. this._data[key] = value;
  68401. return true;
  68402. };
  68403. /**
  68404. * Get the element of the given key and remove it from the dictionary
  68405. * @param key
  68406. */
  68407. StringDictionary.prototype.getAndRemove = function (key) {
  68408. var val = this.get(key);
  68409. if (val !== undefined) {
  68410. delete this._data[key];
  68411. --this._count;
  68412. return val;
  68413. }
  68414. return null;
  68415. };
  68416. /**
  68417. * Remove a key/value from the dictionary.
  68418. * @param key the key to remove
  68419. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68420. */
  68421. StringDictionary.prototype.remove = function (key) {
  68422. if (this.contains(key)) {
  68423. delete this._data[key];
  68424. --this._count;
  68425. return true;
  68426. }
  68427. return false;
  68428. };
  68429. /**
  68430. * Clear the whole content of the dictionary
  68431. */
  68432. StringDictionary.prototype.clear = function () {
  68433. this._data = {};
  68434. this._count = 0;
  68435. };
  68436. Object.defineProperty(StringDictionary.prototype, "count", {
  68437. get: function () {
  68438. return this._count;
  68439. },
  68440. enumerable: true,
  68441. configurable: true
  68442. });
  68443. /**
  68444. * Execute a callback on each key/val of the dictionary.
  68445. * Note that you can remove any element in this dictionary in the callback implementation
  68446. * @param callback the callback to execute on a given key/value pair
  68447. */
  68448. StringDictionary.prototype.forEach = function (callback) {
  68449. for (var cur in this._data) {
  68450. var val = this._data[cur];
  68451. callback(cur, val);
  68452. }
  68453. };
  68454. /**
  68455. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68456. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68457. * Note that you can remove any element in this dictionary in the callback implementation
  68458. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68459. */
  68460. StringDictionary.prototype.first = function (callback) {
  68461. for (var cur in this._data) {
  68462. var val = this._data[cur];
  68463. var res = callback(cur, val);
  68464. if (res) {
  68465. return res;
  68466. }
  68467. }
  68468. return null;
  68469. };
  68470. return StringDictionary;
  68471. }());
  68472. BABYLON.StringDictionary = StringDictionary;
  68473. })(BABYLON || (BABYLON = {}));
  68474. //# sourceMappingURL=babylon.stringDictionary.js.map
  68475. var BABYLON;
  68476. (function (BABYLON) {
  68477. var Tags = /** @class */ (function () {
  68478. function Tags() {
  68479. }
  68480. Tags.EnableFor = function (obj) {
  68481. obj._tags = obj._tags || {};
  68482. obj.hasTags = function () {
  68483. return Tags.HasTags(obj);
  68484. };
  68485. obj.addTags = function (tagsString) {
  68486. return Tags.AddTagsTo(obj, tagsString);
  68487. };
  68488. obj.removeTags = function (tagsString) {
  68489. return Tags.RemoveTagsFrom(obj, tagsString);
  68490. };
  68491. obj.matchesTagsQuery = function (tagsQuery) {
  68492. return Tags.MatchesQuery(obj, tagsQuery);
  68493. };
  68494. };
  68495. Tags.DisableFor = function (obj) {
  68496. delete obj._tags;
  68497. delete obj.hasTags;
  68498. delete obj.addTags;
  68499. delete obj.removeTags;
  68500. delete obj.matchesTagsQuery;
  68501. };
  68502. Tags.HasTags = function (obj) {
  68503. if (!obj._tags) {
  68504. return false;
  68505. }
  68506. return !BABYLON.Tools.IsEmpty(obj._tags);
  68507. };
  68508. Tags.GetTags = function (obj, asString) {
  68509. if (asString === void 0) { asString = true; }
  68510. if (!obj._tags) {
  68511. return null;
  68512. }
  68513. if (asString) {
  68514. var tagsArray = [];
  68515. for (var tag in obj._tags) {
  68516. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68517. tagsArray.push(tag);
  68518. }
  68519. }
  68520. return tagsArray.join(" ");
  68521. }
  68522. else {
  68523. return obj._tags;
  68524. }
  68525. };
  68526. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68527. // a tag cannot start with '||', '&&', and '!'
  68528. // it cannot contain whitespaces
  68529. Tags.AddTagsTo = function (obj, tagsString) {
  68530. if (!tagsString) {
  68531. return;
  68532. }
  68533. if (typeof tagsString !== "string") {
  68534. return;
  68535. }
  68536. var tags = tagsString.split(" ");
  68537. tags.forEach(function (tag, index, array) {
  68538. Tags._AddTagTo(obj, tag);
  68539. });
  68540. };
  68541. Tags._AddTagTo = function (obj, tag) {
  68542. tag = tag.trim();
  68543. if (tag === "" || tag === "true" || tag === "false") {
  68544. return;
  68545. }
  68546. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68547. return;
  68548. }
  68549. Tags.EnableFor(obj);
  68550. obj._tags[tag] = true;
  68551. };
  68552. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68553. if (!Tags.HasTags(obj)) {
  68554. return;
  68555. }
  68556. var tags = tagsString.split(" ");
  68557. for (var t in tags) {
  68558. Tags._RemoveTagFrom(obj, tags[t]);
  68559. }
  68560. };
  68561. Tags._RemoveTagFrom = function (obj, tag) {
  68562. delete obj._tags[tag];
  68563. };
  68564. Tags.MatchesQuery = function (obj, tagsQuery) {
  68565. if (tagsQuery === undefined) {
  68566. return true;
  68567. }
  68568. if (tagsQuery === "") {
  68569. return Tags.HasTags(obj);
  68570. }
  68571. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68572. };
  68573. return Tags;
  68574. }());
  68575. BABYLON.Tags = Tags;
  68576. })(BABYLON || (BABYLON = {}));
  68577. //# sourceMappingURL=babylon.tags.js.map
  68578. var BABYLON;
  68579. (function (BABYLON) {
  68580. /**
  68581. * Class used to evalaute queries containing `and` and `or` operators
  68582. */
  68583. var AndOrNotEvaluator = /** @class */ (function () {
  68584. function AndOrNotEvaluator() {
  68585. }
  68586. /**
  68587. * Evaluate a query
  68588. * @param query defines the query to evaluate
  68589. * @param evaluateCallback defines the callback used to filter result
  68590. * @returns true if the query matches
  68591. */
  68592. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68593. if (!query.match(/\([^\(\)]*\)/g)) {
  68594. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68595. }
  68596. else {
  68597. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68598. // remove parenthesis
  68599. r = r.slice(1, r.length - 1);
  68600. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68601. });
  68602. }
  68603. if (query === "true") {
  68604. return true;
  68605. }
  68606. if (query === "false") {
  68607. return false;
  68608. }
  68609. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68610. };
  68611. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68612. evaluateCallback = evaluateCallback || (function (r) {
  68613. return r === "true" ? true : false;
  68614. });
  68615. var result;
  68616. var or = parenthesisContent.split("||");
  68617. for (var i in or) {
  68618. if (or.hasOwnProperty(i)) {
  68619. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68620. var and = ori.split("&&");
  68621. if (and.length > 1) {
  68622. for (var j = 0; j < and.length; ++j) {
  68623. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68624. if (andj !== "true" && andj !== "false") {
  68625. if (andj[0] === "!") {
  68626. result = !evaluateCallback(andj.substring(1));
  68627. }
  68628. else {
  68629. result = evaluateCallback(andj);
  68630. }
  68631. }
  68632. else {
  68633. result = andj === "true" ? true : false;
  68634. }
  68635. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68636. ori = "false";
  68637. break;
  68638. }
  68639. }
  68640. }
  68641. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68642. result = true;
  68643. break;
  68644. }
  68645. // result equals false (or undefined)
  68646. if (ori !== "true" && ori !== "false") {
  68647. if (ori[0] === "!") {
  68648. result = !evaluateCallback(ori.substring(1));
  68649. }
  68650. else {
  68651. result = evaluateCallback(ori);
  68652. }
  68653. }
  68654. else {
  68655. result = ori === "true" ? true : false;
  68656. }
  68657. }
  68658. }
  68659. // the whole parenthesis scope is replaced by 'true' or 'false'
  68660. return result ? "true" : "false";
  68661. };
  68662. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68663. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68664. // remove whitespaces
  68665. r = r.replace(/[\s]/g, function () { return ""; });
  68666. return r.length % 2 ? "!" : "";
  68667. });
  68668. booleanString = booleanString.trim();
  68669. if (booleanString === "!true") {
  68670. booleanString = "false";
  68671. }
  68672. else if (booleanString === "!false") {
  68673. booleanString = "true";
  68674. }
  68675. return booleanString;
  68676. };
  68677. return AndOrNotEvaluator;
  68678. }());
  68679. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68680. })(BABYLON || (BABYLON = {}));
  68681. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68682. var BABYLON;
  68683. (function (BABYLON) {
  68684. /**
  68685. * Class used to enable access to IndexedDB
  68686. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68687. */
  68688. var Database = /** @class */ (function () {
  68689. /**
  68690. * Creates a new Database
  68691. * @param urlToScene defines the url to load the scene
  68692. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68693. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68694. */
  68695. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68696. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68697. var _this = this;
  68698. // Handling various flavors of prefixed version of IndexedDB
  68699. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68700. this.callbackManifestChecked = callbackManifestChecked;
  68701. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68702. this.db = null;
  68703. this._enableSceneOffline = false;
  68704. this._enableTexturesOffline = false;
  68705. this.manifestVersionFound = 0;
  68706. this.mustUpdateRessources = false;
  68707. this.hasReachedQuota = false;
  68708. if (!Database.IDBStorageEnabled) {
  68709. this.callbackManifestChecked(true);
  68710. }
  68711. else {
  68712. if (disableManifestCheck) {
  68713. this._enableSceneOffline = true;
  68714. this._enableTexturesOffline = true;
  68715. this.manifestVersionFound = 1;
  68716. BABYLON.Tools.SetImmediate(function () {
  68717. _this.callbackManifestChecked(true);
  68718. });
  68719. }
  68720. else {
  68721. this._checkManifestFile();
  68722. }
  68723. }
  68724. }
  68725. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68726. /**
  68727. * Gets a boolean indicating if scene must be saved in the database
  68728. */
  68729. get: function () {
  68730. return this._enableSceneOffline;
  68731. },
  68732. enumerable: true,
  68733. configurable: true
  68734. });
  68735. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68736. /**
  68737. * Gets a boolean indicating if textures must be saved in the database
  68738. */
  68739. get: function () {
  68740. return this._enableTexturesOffline;
  68741. },
  68742. enumerable: true,
  68743. configurable: true
  68744. });
  68745. Database.prototype._checkManifestFile = function () {
  68746. var _this = this;
  68747. var noManifestFile = function () {
  68748. _this._enableSceneOffline = false;
  68749. _this._enableTexturesOffline = false;
  68750. _this.callbackManifestChecked(false);
  68751. };
  68752. var timeStampUsed = false;
  68753. var manifestURL = this.currentSceneUrl + ".manifest";
  68754. var xhr = new XMLHttpRequest();
  68755. if (navigator.onLine) {
  68756. // Adding a timestamp to by-pass browsers' cache
  68757. timeStampUsed = true;
  68758. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68759. }
  68760. xhr.open("GET", manifestURL, true);
  68761. xhr.addEventListener("load", function () {
  68762. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68763. try {
  68764. var manifestFile = JSON.parse(xhr.response);
  68765. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68766. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68767. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68768. _this.manifestVersionFound = manifestFile.version;
  68769. }
  68770. if (_this.callbackManifestChecked) {
  68771. _this.callbackManifestChecked(true);
  68772. }
  68773. }
  68774. catch (ex) {
  68775. noManifestFile();
  68776. }
  68777. }
  68778. else {
  68779. noManifestFile();
  68780. }
  68781. }, false);
  68782. xhr.addEventListener("error", function (event) {
  68783. if (timeStampUsed) {
  68784. timeStampUsed = false;
  68785. // Let's retry without the timeStamp
  68786. // It could fail when coupled with HTML5 Offline API
  68787. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68788. xhr.open("GET", retryManifestURL, true);
  68789. xhr.send();
  68790. }
  68791. else {
  68792. noManifestFile();
  68793. }
  68794. }, false);
  68795. try {
  68796. xhr.send();
  68797. }
  68798. catch (ex) {
  68799. BABYLON.Tools.Error("Error on XHR send request.");
  68800. this.callbackManifestChecked(false);
  68801. }
  68802. };
  68803. /**
  68804. * Open the database and make it available
  68805. * @param successCallback defines the callback to call on success
  68806. * @param errorCallback defines the callback to call on error
  68807. */
  68808. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68809. var _this = this;
  68810. var handleError = function () {
  68811. _this.isSupported = false;
  68812. if (errorCallback)
  68813. errorCallback();
  68814. };
  68815. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68816. // Your browser doesn't support IndexedDB
  68817. this.isSupported = false;
  68818. if (errorCallback)
  68819. errorCallback();
  68820. }
  68821. else {
  68822. // If the DB hasn't been opened or created yet
  68823. if (!this.db) {
  68824. this.hasReachedQuota = false;
  68825. this.isSupported = true;
  68826. var request = this.idbFactory.open("babylonjs", 1);
  68827. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68828. request.onerror = function (event) {
  68829. handleError();
  68830. };
  68831. // executes when a version change transaction cannot complete due to other active transactions
  68832. request.onblocked = function (event) {
  68833. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68834. handleError();
  68835. };
  68836. // DB has been opened successfully
  68837. request.onsuccess = function (event) {
  68838. _this.db = request.result;
  68839. successCallback();
  68840. };
  68841. // Initialization of the DB. Creating Scenes & Textures stores
  68842. request.onupgradeneeded = function (event) {
  68843. _this.db = (event.target).result;
  68844. if (_this.db) {
  68845. try {
  68846. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68847. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68848. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68849. }
  68850. catch (ex) {
  68851. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68852. handleError();
  68853. }
  68854. }
  68855. };
  68856. }
  68857. // DB has already been created and opened
  68858. else {
  68859. if (successCallback)
  68860. successCallback();
  68861. }
  68862. }
  68863. };
  68864. /**
  68865. * Loads an image from the database
  68866. * @param url defines the url to load from
  68867. * @param image defines the target DOM image
  68868. */
  68869. Database.prototype.loadImageFromDB = function (url, image) {
  68870. var _this = this;
  68871. var completeURL = Database._ReturnFullUrlLocation(url);
  68872. var saveAndLoadImage = function () {
  68873. if (!_this.hasReachedQuota && _this.db !== null) {
  68874. // the texture is not yet in the DB, let's try to save it
  68875. _this._saveImageIntoDBAsync(completeURL, image);
  68876. }
  68877. // If the texture is not in the DB and we've reached the DB quota limit
  68878. // let's load it directly from the web
  68879. else {
  68880. image.src = url;
  68881. }
  68882. };
  68883. if (!this.mustUpdateRessources) {
  68884. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68885. }
  68886. // First time we're download the images or update requested in the manifest file by a version change
  68887. else {
  68888. saveAndLoadImage();
  68889. }
  68890. };
  68891. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68892. if (this.isSupported && this.db !== null) {
  68893. var texture;
  68894. var transaction = this.db.transaction(["textures"]);
  68895. transaction.onabort = function (event) {
  68896. image.src = url;
  68897. };
  68898. transaction.oncomplete = function (event) {
  68899. var blobTextureURL;
  68900. if (texture) {
  68901. var URL = window.URL || window.webkitURL;
  68902. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68903. image.onerror = function () {
  68904. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68905. image.src = url;
  68906. };
  68907. image.src = blobTextureURL;
  68908. }
  68909. else {
  68910. notInDBCallback();
  68911. }
  68912. };
  68913. var getRequest = transaction.objectStore("textures").get(url);
  68914. getRequest.onsuccess = function (event) {
  68915. texture = (event.target).result;
  68916. };
  68917. getRequest.onerror = function (event) {
  68918. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68919. image.src = url;
  68920. };
  68921. }
  68922. else {
  68923. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68924. image.src = url;
  68925. }
  68926. };
  68927. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68928. var _this = this;
  68929. if (this.isSupported) {
  68930. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68931. var generateBlobUrl = function () {
  68932. var blobTextureURL;
  68933. if (blob) {
  68934. var URL = window.URL || window.webkitURL;
  68935. try {
  68936. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68937. }
  68938. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68939. catch (ex) {
  68940. blobTextureURL = URL.createObjectURL(blob);
  68941. }
  68942. }
  68943. if (blobTextureURL) {
  68944. image.src = blobTextureURL;
  68945. }
  68946. };
  68947. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68948. var xhr = new XMLHttpRequest(), blob;
  68949. xhr.open("GET", url, true);
  68950. xhr.responseType = "blob";
  68951. xhr.addEventListener("load", function () {
  68952. if (xhr.status === 200 && _this.db) {
  68953. // Blob as response (XHR2)
  68954. blob = xhr.response;
  68955. var transaction = _this.db.transaction(["textures"], "readwrite");
  68956. // the transaction could abort because of a QuotaExceededError error
  68957. transaction.onabort = function (event) {
  68958. try {
  68959. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68960. var srcElement = (event.srcElement || event.target);
  68961. var error = srcElement.error;
  68962. if (error && error.name === "QuotaExceededError") {
  68963. _this.hasReachedQuota = true;
  68964. }
  68965. }
  68966. catch (ex) { }
  68967. generateBlobUrl();
  68968. };
  68969. transaction.oncomplete = function (event) {
  68970. generateBlobUrl();
  68971. };
  68972. var newTexture = { textureUrl: url, data: blob };
  68973. try {
  68974. // Put the blob into the dabase
  68975. var addRequest = transaction.objectStore("textures").put(newTexture);
  68976. addRequest.onsuccess = function (event) {
  68977. };
  68978. addRequest.onerror = function (event) {
  68979. generateBlobUrl();
  68980. };
  68981. }
  68982. catch (ex) {
  68983. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68984. if (ex.code === 25) {
  68985. Database.IsUASupportingBlobStorage = false;
  68986. }
  68987. image.src = url;
  68988. }
  68989. }
  68990. else {
  68991. image.src = url;
  68992. }
  68993. }, false);
  68994. xhr.addEventListener("error", function (event) {
  68995. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68996. image.src = url;
  68997. }, false);
  68998. xhr.send();
  68999. }
  69000. else {
  69001. image.src = url;
  69002. }
  69003. }
  69004. else {
  69005. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69006. image.src = url;
  69007. }
  69008. };
  69009. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69010. var _this = this;
  69011. var updateVersion = function () {
  69012. // the version is not yet in the DB or we need to update it
  69013. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69014. };
  69015. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69016. };
  69017. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69018. var _this = this;
  69019. if (this.isSupported && this.db) {
  69020. var version;
  69021. try {
  69022. var transaction = this.db.transaction(["versions"]);
  69023. transaction.oncomplete = function (event) {
  69024. if (version) {
  69025. // If the version in the JSON file is different from the version in DB
  69026. if (_this.manifestVersionFound !== version.data) {
  69027. _this.mustUpdateRessources = true;
  69028. updateInDBCallback();
  69029. }
  69030. else {
  69031. callback(version.data);
  69032. }
  69033. }
  69034. // version was not found in DB
  69035. else {
  69036. _this.mustUpdateRessources = true;
  69037. updateInDBCallback();
  69038. }
  69039. };
  69040. transaction.onabort = function (event) {
  69041. callback(-1);
  69042. };
  69043. var getRequest = transaction.objectStore("versions").get(url);
  69044. getRequest.onsuccess = function (event) {
  69045. version = (event.target).result;
  69046. };
  69047. getRequest.onerror = function (event) {
  69048. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69049. callback(-1);
  69050. };
  69051. }
  69052. catch (ex) {
  69053. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69054. callback(-1);
  69055. }
  69056. }
  69057. else {
  69058. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69059. callback(-1);
  69060. }
  69061. };
  69062. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69063. var _this = this;
  69064. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69065. try {
  69066. // Open a transaction to the database
  69067. var transaction = this.db.transaction(["versions"], "readwrite");
  69068. // the transaction could abort because of a QuotaExceededError error
  69069. transaction.onabort = function (event) {
  69070. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69071. var error = event.srcElement['error'];
  69072. if (error && error.name === "QuotaExceededError") {
  69073. _this.hasReachedQuota = true;
  69074. }
  69075. }
  69076. catch (ex) { }
  69077. callback(-1);
  69078. };
  69079. transaction.oncomplete = function (event) {
  69080. callback(_this.manifestVersionFound);
  69081. };
  69082. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69083. // Put the scene into the database
  69084. var addRequest = transaction.objectStore("versions").put(newVersion);
  69085. addRequest.onsuccess = function (event) {
  69086. };
  69087. addRequest.onerror = function (event) {
  69088. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69089. };
  69090. }
  69091. catch (ex) {
  69092. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69093. callback(-1);
  69094. }
  69095. }
  69096. else {
  69097. callback(-1);
  69098. }
  69099. };
  69100. /**
  69101. * Loads a file from database
  69102. * @param url defines the URL to load from
  69103. * @param sceneLoaded defines a callback to call on success
  69104. * @param progressCallBack defines a callback to call when progress changed
  69105. * @param errorCallback defines a callback to call on error
  69106. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69107. */
  69108. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69109. var _this = this;
  69110. var completeUrl = Database._ReturnFullUrlLocation(url);
  69111. var saveAndLoadFile = function () {
  69112. // the scene is not yet in the DB, let's try to save it
  69113. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69114. };
  69115. this._checkVersionFromDB(completeUrl, function (version) {
  69116. if (version !== -1) {
  69117. if (!_this.mustUpdateRessources) {
  69118. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69119. }
  69120. else {
  69121. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69122. }
  69123. }
  69124. else {
  69125. if (errorCallback) {
  69126. errorCallback();
  69127. }
  69128. }
  69129. });
  69130. };
  69131. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69132. if (this.isSupported && this.db) {
  69133. var targetStore;
  69134. if (url.indexOf(".babylon") !== -1) {
  69135. targetStore = "scenes";
  69136. }
  69137. else {
  69138. targetStore = "textures";
  69139. }
  69140. var file;
  69141. var transaction = this.db.transaction([targetStore]);
  69142. transaction.oncomplete = function (event) {
  69143. if (file) {
  69144. callback(file.data);
  69145. }
  69146. // file was not found in DB
  69147. else {
  69148. notInDBCallback();
  69149. }
  69150. };
  69151. transaction.onabort = function (event) {
  69152. notInDBCallback();
  69153. };
  69154. var getRequest = transaction.objectStore(targetStore).get(url);
  69155. getRequest.onsuccess = function (event) {
  69156. file = (event.target).result;
  69157. };
  69158. getRequest.onerror = function (event) {
  69159. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69160. notInDBCallback();
  69161. };
  69162. }
  69163. else {
  69164. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69165. callback();
  69166. }
  69167. };
  69168. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69169. var _this = this;
  69170. if (this.isSupported) {
  69171. var targetStore;
  69172. if (url.indexOf(".babylon") !== -1) {
  69173. targetStore = "scenes";
  69174. }
  69175. else {
  69176. targetStore = "textures";
  69177. }
  69178. // Create XHR
  69179. var xhr = new XMLHttpRequest();
  69180. var fileData;
  69181. xhr.open("GET", url, true);
  69182. if (useArrayBuffer) {
  69183. xhr.responseType = "arraybuffer";
  69184. }
  69185. if (progressCallback) {
  69186. xhr.onprogress = progressCallback;
  69187. }
  69188. xhr.addEventListener("load", function () {
  69189. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69190. // Blob as response (XHR2)
  69191. //fileData = xhr.responseText;
  69192. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69193. if (!_this.hasReachedQuota && _this.db) {
  69194. // Open a transaction to the database
  69195. var transaction = _this.db.transaction([targetStore], "readwrite");
  69196. // the transaction could abort because of a QuotaExceededError error
  69197. transaction.onabort = function (event) {
  69198. try {
  69199. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69200. var error = event.srcElement['error'];
  69201. if (error && error.name === "QuotaExceededError") {
  69202. _this.hasReachedQuota = true;
  69203. }
  69204. }
  69205. catch (ex) { }
  69206. callback(fileData);
  69207. };
  69208. transaction.oncomplete = function (event) {
  69209. callback(fileData);
  69210. };
  69211. var newFile;
  69212. if (targetStore === "scenes") {
  69213. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69214. }
  69215. else {
  69216. newFile = { textureUrl: url, data: fileData };
  69217. }
  69218. try {
  69219. // Put the scene into the database
  69220. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69221. addRequest.onsuccess = function (event) {
  69222. };
  69223. addRequest.onerror = function (event) {
  69224. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69225. };
  69226. }
  69227. catch (ex) {
  69228. callback(fileData);
  69229. }
  69230. }
  69231. else {
  69232. callback(fileData);
  69233. }
  69234. }
  69235. else {
  69236. callback();
  69237. }
  69238. }, false);
  69239. xhr.addEventListener("error", function (event) {
  69240. BABYLON.Tools.Error("error on XHR request.");
  69241. callback();
  69242. }, false);
  69243. xhr.send();
  69244. }
  69245. else {
  69246. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69247. callback();
  69248. }
  69249. };
  69250. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69251. Database.IsUASupportingBlobStorage = true;
  69252. /** Gets a boolean indicating if Database storate is enabled */
  69253. Database.IDBStorageEnabled = true;
  69254. Database._ParseURL = function (url) {
  69255. var a = document.createElement('a');
  69256. a.href = url;
  69257. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69258. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69259. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69260. return absLocation;
  69261. };
  69262. Database._ReturnFullUrlLocation = function (url) {
  69263. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69264. return (Database._ParseURL(window.location.href) + url);
  69265. }
  69266. else {
  69267. return url;
  69268. }
  69269. };
  69270. return Database;
  69271. }());
  69272. BABYLON.Database = Database;
  69273. })(BABYLON || (BABYLON = {}));
  69274. //# sourceMappingURL=babylon.database.js.map
  69275. var BABYLON;
  69276. (function (BABYLON) {
  69277. var FresnelParameters = /** @class */ (function () {
  69278. function FresnelParameters() {
  69279. this._isEnabled = true;
  69280. this.leftColor = BABYLON.Color3.White();
  69281. this.rightColor = BABYLON.Color3.Black();
  69282. this.bias = 0;
  69283. this.power = 1;
  69284. }
  69285. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69286. get: function () {
  69287. return this._isEnabled;
  69288. },
  69289. set: function (value) {
  69290. if (this._isEnabled === value) {
  69291. return;
  69292. }
  69293. this._isEnabled = value;
  69294. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69295. },
  69296. enumerable: true,
  69297. configurable: true
  69298. });
  69299. FresnelParameters.prototype.clone = function () {
  69300. var newFresnelParameters = new FresnelParameters();
  69301. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69302. return newFresnelParameters;
  69303. };
  69304. FresnelParameters.prototype.serialize = function () {
  69305. var serializationObject = {};
  69306. serializationObject.isEnabled = this.isEnabled;
  69307. serializationObject.leftColor = this.leftColor.asArray();
  69308. serializationObject.rightColor = this.rightColor.asArray();
  69309. serializationObject.bias = this.bias;
  69310. serializationObject.power = this.power;
  69311. return serializationObject;
  69312. };
  69313. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69314. var fresnelParameters = new FresnelParameters();
  69315. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69316. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69317. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69318. fresnelParameters.bias = parsedFresnelParameters.bias;
  69319. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69320. return fresnelParameters;
  69321. };
  69322. return FresnelParameters;
  69323. }());
  69324. BABYLON.FresnelParameters = FresnelParameters;
  69325. })(BABYLON || (BABYLON = {}));
  69326. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69327. var BABYLON;
  69328. (function (BABYLON) {
  69329. var MultiMaterial = /** @class */ (function (_super) {
  69330. __extends(MultiMaterial, _super);
  69331. function MultiMaterial(name, scene) {
  69332. var _this = _super.call(this, name, scene, true) || this;
  69333. scene.multiMaterials.push(_this);
  69334. _this.subMaterials = new Array();
  69335. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69336. return _this;
  69337. }
  69338. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69339. get: function () {
  69340. return this._subMaterials;
  69341. },
  69342. set: function (value) {
  69343. this._subMaterials = value;
  69344. this._hookArray(value);
  69345. },
  69346. enumerable: true,
  69347. configurable: true
  69348. });
  69349. MultiMaterial.prototype._hookArray = function (array) {
  69350. var _this = this;
  69351. var oldPush = array.push;
  69352. array.push = function () {
  69353. var items = [];
  69354. for (var _i = 0; _i < arguments.length; _i++) {
  69355. items[_i] = arguments[_i];
  69356. }
  69357. var result = oldPush.apply(array, items);
  69358. _this._markAllSubMeshesAsTexturesDirty();
  69359. return result;
  69360. };
  69361. var oldSplice = array.splice;
  69362. array.splice = function (index, deleteCount) {
  69363. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69364. _this._markAllSubMeshesAsTexturesDirty();
  69365. return deleted;
  69366. };
  69367. };
  69368. // Properties
  69369. MultiMaterial.prototype.getSubMaterial = function (index) {
  69370. if (index < 0 || index >= this.subMaterials.length) {
  69371. return this.getScene().defaultMaterial;
  69372. }
  69373. return this.subMaterials[index];
  69374. };
  69375. MultiMaterial.prototype.getActiveTextures = function () {
  69376. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69377. if (subMaterial) {
  69378. return subMaterial.getActiveTextures();
  69379. }
  69380. else {
  69381. return [];
  69382. }
  69383. }));
  69384. var _a;
  69385. };
  69386. // Methods
  69387. MultiMaterial.prototype.getClassName = function () {
  69388. return "MultiMaterial";
  69389. };
  69390. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69391. for (var index = 0; index < this.subMaterials.length; index++) {
  69392. var subMaterial = this.subMaterials[index];
  69393. if (subMaterial) {
  69394. if (subMaterial.storeEffectOnSubMeshes) {
  69395. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69396. return false;
  69397. }
  69398. continue;
  69399. }
  69400. if (!subMaterial.isReady(mesh)) {
  69401. return false;
  69402. }
  69403. }
  69404. }
  69405. return true;
  69406. };
  69407. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69408. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69409. for (var index = 0; index < this.subMaterials.length; index++) {
  69410. var subMaterial = null;
  69411. var current = this.subMaterials[index];
  69412. if (cloneChildren && current) {
  69413. subMaterial = current.clone(name + "-" + current.name);
  69414. }
  69415. else {
  69416. subMaterial = this.subMaterials[index];
  69417. }
  69418. newMultiMaterial.subMaterials.push(subMaterial);
  69419. }
  69420. return newMultiMaterial;
  69421. };
  69422. MultiMaterial.prototype.serialize = function () {
  69423. var serializationObject = {};
  69424. serializationObject.name = this.name;
  69425. serializationObject.id = this.id;
  69426. if (BABYLON.Tags) {
  69427. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69428. }
  69429. serializationObject.materials = [];
  69430. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69431. var subMat = this.subMaterials[matIndex];
  69432. if (subMat) {
  69433. serializationObject.materials.push(subMat.id);
  69434. }
  69435. else {
  69436. serializationObject.materials.push(null);
  69437. }
  69438. }
  69439. return serializationObject;
  69440. };
  69441. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69442. var scene = this.getScene();
  69443. if (!scene) {
  69444. return;
  69445. }
  69446. var index = scene.multiMaterials.indexOf(this);
  69447. if (index >= 0) {
  69448. scene.multiMaterials.splice(index, 1);
  69449. }
  69450. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69451. };
  69452. return MultiMaterial;
  69453. }(BABYLON.Material));
  69454. BABYLON.MultiMaterial = MultiMaterial;
  69455. })(BABYLON || (BABYLON = {}));
  69456. //# sourceMappingURL=babylon.multiMaterial.js.map
  69457. var BABYLON;
  69458. (function (BABYLON) {
  69459. var FreeCameraTouchInput = /** @class */ (function () {
  69460. function FreeCameraTouchInput() {
  69461. this._offsetX = null;
  69462. this._offsetY = null;
  69463. this._pointerPressed = new Array();
  69464. this.touchAngularSensibility = 200000.0;
  69465. this.touchMoveSensibility = 250.0;
  69466. }
  69467. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69468. var _this = this;
  69469. var previousPosition = null;
  69470. if (this._pointerInput === undefined) {
  69471. this._onLostFocus = function (evt) {
  69472. _this._offsetX = null;
  69473. _this._offsetY = null;
  69474. };
  69475. this._pointerInput = function (p, s) {
  69476. var evt = p.event;
  69477. if (evt.pointerType === "mouse") {
  69478. return;
  69479. }
  69480. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69481. if (!noPreventDefault) {
  69482. evt.preventDefault();
  69483. }
  69484. _this._pointerPressed.push(evt.pointerId);
  69485. if (_this._pointerPressed.length !== 1) {
  69486. return;
  69487. }
  69488. previousPosition = {
  69489. x: evt.clientX,
  69490. y: evt.clientY
  69491. };
  69492. }
  69493. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69494. if (!noPreventDefault) {
  69495. evt.preventDefault();
  69496. }
  69497. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69498. if (index === -1) {
  69499. return;
  69500. }
  69501. _this._pointerPressed.splice(index, 1);
  69502. if (index != 0) {
  69503. return;
  69504. }
  69505. previousPosition = null;
  69506. _this._offsetX = null;
  69507. _this._offsetY = null;
  69508. }
  69509. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69510. if (!noPreventDefault) {
  69511. evt.preventDefault();
  69512. }
  69513. if (!previousPosition) {
  69514. return;
  69515. }
  69516. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69517. if (index != 0) {
  69518. return;
  69519. }
  69520. _this._offsetX = evt.clientX - previousPosition.x;
  69521. _this._offsetY = -(evt.clientY - previousPosition.y);
  69522. }
  69523. };
  69524. }
  69525. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69526. if (this._onLostFocus) {
  69527. element.addEventListener("blur", this._onLostFocus);
  69528. }
  69529. };
  69530. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69531. if (this._pointerInput && element) {
  69532. if (this._observer) {
  69533. this.camera.getScene().onPointerObservable.remove(this._observer);
  69534. this._observer = null;
  69535. }
  69536. if (this._onLostFocus) {
  69537. element.removeEventListener("blur", this._onLostFocus);
  69538. this._onLostFocus = null;
  69539. }
  69540. this._pointerPressed = [];
  69541. this._offsetX = null;
  69542. this._offsetY = null;
  69543. }
  69544. };
  69545. FreeCameraTouchInput.prototype.checkInputs = function () {
  69546. if (this._offsetX && this._offsetY) {
  69547. var camera = this.camera;
  69548. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69549. if (this._pointerPressed.length > 1) {
  69550. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69551. }
  69552. else {
  69553. var speed = camera._computeLocalCameraSpeed();
  69554. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69555. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69556. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69557. }
  69558. }
  69559. };
  69560. FreeCameraTouchInput.prototype.getClassName = function () {
  69561. return "FreeCameraTouchInput";
  69562. };
  69563. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69564. return "touch";
  69565. };
  69566. __decorate([
  69567. BABYLON.serialize()
  69568. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69569. __decorate([
  69570. BABYLON.serialize()
  69571. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69572. return FreeCameraTouchInput;
  69573. }());
  69574. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69575. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69576. })(BABYLON || (BABYLON = {}));
  69577. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69578. var BABYLON;
  69579. (function (BABYLON) {
  69580. // We're mainly based on the logic defined into the FreeCamera code
  69581. var TouchCamera = /** @class */ (function (_super) {
  69582. __extends(TouchCamera, _super);
  69583. //-- end properties for backward compatibility for inputs
  69584. function TouchCamera(name, position, scene) {
  69585. var _this = _super.call(this, name, position, scene) || this;
  69586. _this.inputs.addTouch();
  69587. _this._setupInputs();
  69588. return _this;
  69589. }
  69590. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69591. //-- Begin properties for backward compatibility for inputs
  69592. get: function () {
  69593. var touch = this.inputs.attached["touch"];
  69594. if (touch)
  69595. return touch.touchAngularSensibility;
  69596. return 0;
  69597. },
  69598. set: function (value) {
  69599. var touch = this.inputs.attached["touch"];
  69600. if (touch)
  69601. touch.touchAngularSensibility = value;
  69602. },
  69603. enumerable: true,
  69604. configurable: true
  69605. });
  69606. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69607. get: function () {
  69608. var touch = this.inputs.attached["touch"];
  69609. if (touch)
  69610. return touch.touchMoveSensibility;
  69611. return 0;
  69612. },
  69613. set: function (value) {
  69614. var touch = this.inputs.attached["touch"];
  69615. if (touch)
  69616. touch.touchMoveSensibility = value;
  69617. },
  69618. enumerable: true,
  69619. configurable: true
  69620. });
  69621. TouchCamera.prototype.getClassName = function () {
  69622. return "TouchCamera";
  69623. };
  69624. TouchCamera.prototype._setupInputs = function () {
  69625. var mouse = this.inputs.attached["mouse"];
  69626. if (mouse) {
  69627. mouse.touchEnabled = false;
  69628. }
  69629. };
  69630. return TouchCamera;
  69631. }(BABYLON.FreeCamera));
  69632. BABYLON.TouchCamera = TouchCamera;
  69633. })(BABYLON || (BABYLON = {}));
  69634. //# sourceMappingURL=babylon.touchCamera.js.map
  69635. var BABYLON;
  69636. (function (BABYLON) {
  69637. var ProceduralTexture = /** @class */ (function (_super) {
  69638. __extends(ProceduralTexture, _super);
  69639. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69640. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69641. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69642. if (isCube === void 0) { isCube = false; }
  69643. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69644. _this.isCube = isCube;
  69645. _this.isEnabled = true;
  69646. _this._currentRefreshId = -1;
  69647. _this._refreshRate = 1;
  69648. _this._vertexBuffers = {};
  69649. _this._uniforms = new Array();
  69650. _this._samplers = new Array();
  69651. _this._textures = {};
  69652. _this._floats = {};
  69653. _this._floatsArrays = {};
  69654. _this._colors3 = {};
  69655. _this._colors4 = {};
  69656. _this._vectors2 = {};
  69657. _this._vectors3 = {};
  69658. _this._matrices = {};
  69659. _this._fallbackTextureUsed = false;
  69660. scene.proceduralTextures.push(_this);
  69661. _this._engine = scene.getEngine();
  69662. _this.name = name;
  69663. _this.isRenderTarget = true;
  69664. _this._size = size;
  69665. _this._generateMipMaps = generateMipMaps;
  69666. _this.setFragment(fragment);
  69667. _this._fallbackTexture = fallbackTexture;
  69668. if (isCube) {
  69669. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69670. _this.setFloat("face", 0);
  69671. }
  69672. else {
  69673. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69674. }
  69675. // VBO
  69676. var vertices = [];
  69677. vertices.push(1, 1);
  69678. vertices.push(-1, 1);
  69679. vertices.push(-1, -1);
  69680. vertices.push(1, -1);
  69681. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69682. _this._createIndexBuffer();
  69683. return _this;
  69684. }
  69685. ProceduralTexture.prototype._createIndexBuffer = function () {
  69686. var engine = this._engine;
  69687. // Indices
  69688. var indices = [];
  69689. indices.push(0);
  69690. indices.push(1);
  69691. indices.push(2);
  69692. indices.push(0);
  69693. indices.push(2);
  69694. indices.push(3);
  69695. this._indexBuffer = engine.createIndexBuffer(indices);
  69696. };
  69697. ProceduralTexture.prototype._rebuild = function () {
  69698. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69699. if (vb) {
  69700. vb._rebuild();
  69701. }
  69702. this._createIndexBuffer();
  69703. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69704. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69705. }
  69706. };
  69707. ProceduralTexture.prototype.reset = function () {
  69708. if (this._effect === undefined) {
  69709. return;
  69710. }
  69711. var engine = this._engine;
  69712. engine._releaseEffect(this._effect);
  69713. };
  69714. ProceduralTexture.prototype.isReady = function () {
  69715. var _this = this;
  69716. var engine = this._engine;
  69717. var shaders;
  69718. if (!this._fragment) {
  69719. return false;
  69720. }
  69721. if (this._fallbackTextureUsed) {
  69722. return true;
  69723. }
  69724. if (this._fragment.fragmentElement !== undefined) {
  69725. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69726. }
  69727. else {
  69728. shaders = { vertex: "procedural", fragment: this._fragment };
  69729. }
  69730. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69731. _this.releaseInternalTexture();
  69732. if (_this._fallbackTexture) {
  69733. _this._texture = _this._fallbackTexture._texture;
  69734. if (_this._texture) {
  69735. _this._texture.incrementReferences();
  69736. }
  69737. }
  69738. _this._fallbackTextureUsed = true;
  69739. });
  69740. return this._effect.isReady();
  69741. };
  69742. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69743. this._currentRefreshId = -1;
  69744. };
  69745. ProceduralTexture.prototype.setFragment = function (fragment) {
  69746. this._fragment = fragment;
  69747. };
  69748. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69749. get: function () {
  69750. return this._refreshRate;
  69751. },
  69752. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69753. set: function (value) {
  69754. this._refreshRate = value;
  69755. this.resetRefreshCounter();
  69756. },
  69757. enumerable: true,
  69758. configurable: true
  69759. });
  69760. ProceduralTexture.prototype._shouldRender = function () {
  69761. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69762. return false;
  69763. }
  69764. if (this._fallbackTextureUsed) {
  69765. return false;
  69766. }
  69767. if (this._currentRefreshId === -1) { // At least render once
  69768. this._currentRefreshId = 1;
  69769. return true;
  69770. }
  69771. if (this.refreshRate === this._currentRefreshId) {
  69772. this._currentRefreshId = 1;
  69773. return true;
  69774. }
  69775. this._currentRefreshId++;
  69776. return false;
  69777. };
  69778. ProceduralTexture.prototype.getRenderSize = function () {
  69779. return this._size;
  69780. };
  69781. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69782. if (this._fallbackTextureUsed) {
  69783. return;
  69784. }
  69785. this.releaseInternalTexture();
  69786. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69787. };
  69788. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69789. if (this._uniforms.indexOf(uniformName) === -1) {
  69790. this._uniforms.push(uniformName);
  69791. }
  69792. };
  69793. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69794. if (this._samplers.indexOf(name) === -1) {
  69795. this._samplers.push(name);
  69796. }
  69797. this._textures[name] = texture;
  69798. return this;
  69799. };
  69800. ProceduralTexture.prototype.setFloat = function (name, value) {
  69801. this._checkUniform(name);
  69802. this._floats[name] = value;
  69803. return this;
  69804. };
  69805. ProceduralTexture.prototype.setFloats = function (name, value) {
  69806. this._checkUniform(name);
  69807. this._floatsArrays[name] = value;
  69808. return this;
  69809. };
  69810. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69811. this._checkUniform(name);
  69812. this._colors3[name] = value;
  69813. return this;
  69814. };
  69815. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69816. this._checkUniform(name);
  69817. this._colors4[name] = value;
  69818. return this;
  69819. };
  69820. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69821. this._checkUniform(name);
  69822. this._vectors2[name] = value;
  69823. return this;
  69824. };
  69825. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69826. this._checkUniform(name);
  69827. this._vectors3[name] = value;
  69828. return this;
  69829. };
  69830. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69831. this._checkUniform(name);
  69832. this._matrices[name] = value;
  69833. return this;
  69834. };
  69835. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69836. var scene = this.getScene();
  69837. if (!scene) {
  69838. return;
  69839. }
  69840. var engine = this._engine;
  69841. // Render
  69842. engine.enableEffect(this._effect);
  69843. engine.setState(false);
  69844. // Texture
  69845. for (var name in this._textures) {
  69846. this._effect.setTexture(name, this._textures[name]);
  69847. }
  69848. // Float
  69849. for (name in this._floats) {
  69850. this._effect.setFloat(name, this._floats[name]);
  69851. }
  69852. // Floats
  69853. for (name in this._floatsArrays) {
  69854. this._effect.setArray(name, this._floatsArrays[name]);
  69855. }
  69856. // Color3
  69857. for (name in this._colors3) {
  69858. this._effect.setColor3(name, this._colors3[name]);
  69859. }
  69860. // Color4
  69861. for (name in this._colors4) {
  69862. var color = this._colors4[name];
  69863. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69864. }
  69865. // Vector2
  69866. for (name in this._vectors2) {
  69867. this._effect.setVector2(name, this._vectors2[name]);
  69868. }
  69869. // Vector3
  69870. for (name in this._vectors3) {
  69871. this._effect.setVector3(name, this._vectors3[name]);
  69872. }
  69873. // Matrix
  69874. for (name in this._matrices) {
  69875. this._effect.setMatrix(name, this._matrices[name]);
  69876. }
  69877. if (!this._texture) {
  69878. return;
  69879. }
  69880. if (this.isCube) {
  69881. for (var face = 0; face < 6; face++) {
  69882. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69883. // VBOs
  69884. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69885. this._effect.setFloat("face", face);
  69886. // Clear
  69887. engine.clear(scene.clearColor, true, true, true);
  69888. // Draw order
  69889. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69890. // Mipmaps
  69891. if (face === 5) {
  69892. engine.generateMipMapsForCubemap(this._texture);
  69893. }
  69894. }
  69895. }
  69896. else {
  69897. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69898. // VBOs
  69899. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69900. // Clear
  69901. engine.clear(scene.clearColor, true, true, true);
  69902. // Draw order
  69903. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69904. }
  69905. // Unbind
  69906. engine.unBindFramebuffer(this._texture, this.isCube);
  69907. if (this.onGenerated) {
  69908. this.onGenerated();
  69909. }
  69910. };
  69911. ProceduralTexture.prototype.clone = function () {
  69912. var textureSize = this.getSize();
  69913. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69914. // Base texture
  69915. newTexture.hasAlpha = this.hasAlpha;
  69916. newTexture.level = this.level;
  69917. // RenderTarget Texture
  69918. newTexture.coordinatesMode = this.coordinatesMode;
  69919. return newTexture;
  69920. };
  69921. ProceduralTexture.prototype.dispose = function () {
  69922. var scene = this.getScene();
  69923. if (!scene) {
  69924. return;
  69925. }
  69926. var index = scene.proceduralTextures.indexOf(this);
  69927. if (index >= 0) {
  69928. scene.proceduralTextures.splice(index, 1);
  69929. }
  69930. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69931. if (vertexBuffer) {
  69932. vertexBuffer.dispose();
  69933. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69934. }
  69935. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69936. this._indexBuffer = null;
  69937. }
  69938. _super.prototype.dispose.call(this);
  69939. };
  69940. return ProceduralTexture;
  69941. }(BABYLON.Texture));
  69942. BABYLON.ProceduralTexture = ProceduralTexture;
  69943. })(BABYLON || (BABYLON = {}));
  69944. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69945. var BABYLON;
  69946. (function (BABYLON) {
  69947. var CustomProceduralTexture = /** @class */ (function (_super) {
  69948. __extends(CustomProceduralTexture, _super);
  69949. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69950. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69951. _this._animate = true;
  69952. _this._time = 0;
  69953. _this._texturePath = texturePath;
  69954. //Try to load json
  69955. _this.loadJson(texturePath);
  69956. _this.refreshRate = 1;
  69957. return _this;
  69958. }
  69959. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69960. var _this = this;
  69961. var noConfigFile = function () {
  69962. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69963. try {
  69964. _this.setFragment(_this._texturePath);
  69965. }
  69966. catch (ex) {
  69967. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69968. }
  69969. };
  69970. var configFileUrl = jsonUrl + "/config.json";
  69971. var xhr = new XMLHttpRequest();
  69972. xhr.open("GET", configFileUrl, true);
  69973. xhr.addEventListener("load", function () {
  69974. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69975. try {
  69976. _this._config = JSON.parse(xhr.response);
  69977. _this.updateShaderUniforms();
  69978. _this.updateTextures();
  69979. _this.setFragment(_this._texturePath + "/custom");
  69980. _this._animate = _this._config.animate;
  69981. _this.refreshRate = _this._config.refreshrate;
  69982. }
  69983. catch (ex) {
  69984. noConfigFile();
  69985. }
  69986. }
  69987. else {
  69988. noConfigFile();
  69989. }
  69990. }, false);
  69991. xhr.addEventListener("error", function () {
  69992. noConfigFile();
  69993. }, false);
  69994. try {
  69995. xhr.send();
  69996. }
  69997. catch (ex) {
  69998. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69999. }
  70000. };
  70001. CustomProceduralTexture.prototype.isReady = function () {
  70002. if (!_super.prototype.isReady.call(this)) {
  70003. return false;
  70004. }
  70005. for (var name in this._textures) {
  70006. var texture = this._textures[name];
  70007. if (!texture.isReady()) {
  70008. return false;
  70009. }
  70010. }
  70011. return true;
  70012. };
  70013. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70014. var scene = this.getScene();
  70015. if (this._animate && scene) {
  70016. this._time += scene.getAnimationRatio() * 0.03;
  70017. this.updateShaderUniforms();
  70018. }
  70019. _super.prototype.render.call(this, useCameraPostProcess);
  70020. };
  70021. CustomProceduralTexture.prototype.updateTextures = function () {
  70022. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70023. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70024. }
  70025. };
  70026. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70027. if (this._config) {
  70028. for (var j = 0; j < this._config.uniforms.length; j++) {
  70029. var uniform = this._config.uniforms[j];
  70030. switch (uniform.type) {
  70031. case "float":
  70032. this.setFloat(uniform.name, uniform.value);
  70033. break;
  70034. case "color3":
  70035. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70036. break;
  70037. case "color4":
  70038. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70039. break;
  70040. case "vector2":
  70041. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70042. break;
  70043. case "vector3":
  70044. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70045. break;
  70046. }
  70047. }
  70048. }
  70049. this.setFloat("time", this._time);
  70050. };
  70051. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70052. get: function () {
  70053. return this._animate;
  70054. },
  70055. set: function (value) {
  70056. this._animate = value;
  70057. },
  70058. enumerable: true,
  70059. configurable: true
  70060. });
  70061. return CustomProceduralTexture;
  70062. }(BABYLON.ProceduralTexture));
  70063. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70064. })(BABYLON || (BABYLON = {}));
  70065. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70066. var BABYLON;
  70067. (function (BABYLON) {
  70068. var FreeCameraGamepadInput = /** @class */ (function () {
  70069. function FreeCameraGamepadInput() {
  70070. this.gamepadAngularSensibility = 200;
  70071. this.gamepadMoveSensibility = 40;
  70072. // private members
  70073. this._cameraTransform = BABYLON.Matrix.Identity();
  70074. this._deltaTransform = BABYLON.Vector3.Zero();
  70075. this._vector3 = BABYLON.Vector3.Zero();
  70076. this._vector2 = BABYLON.Vector2.Zero();
  70077. }
  70078. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70079. var _this = this;
  70080. var manager = this.camera.getScene().gamepadManager;
  70081. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70082. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70083. // prioritize XBOX gamepads.
  70084. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70085. _this.gamepad = gamepad;
  70086. }
  70087. }
  70088. });
  70089. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70090. if (_this.gamepad === gamepad) {
  70091. _this.gamepad = null;
  70092. }
  70093. });
  70094. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70095. };
  70096. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70097. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70098. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70099. this.gamepad = null;
  70100. };
  70101. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70102. if (this.gamepad && this.gamepad.leftStick) {
  70103. var camera = this.camera;
  70104. var LSValues = this.gamepad.leftStick;
  70105. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70106. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70107. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70108. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70109. var RSValues = this.gamepad.rightStick;
  70110. if (RSValues) {
  70111. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70112. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70113. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70114. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70115. }
  70116. else {
  70117. RSValues = { x: 0, y: 0 };
  70118. }
  70119. if (!camera.rotationQuaternion) {
  70120. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70121. }
  70122. else {
  70123. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70124. }
  70125. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70126. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70127. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70128. camera.cameraDirection.addInPlace(this._deltaTransform);
  70129. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70130. camera.cameraRotation.addInPlace(this._vector2);
  70131. }
  70132. };
  70133. FreeCameraGamepadInput.prototype.getClassName = function () {
  70134. return "FreeCameraGamepadInput";
  70135. };
  70136. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70137. return "gamepad";
  70138. };
  70139. __decorate([
  70140. BABYLON.serialize()
  70141. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70142. __decorate([
  70143. BABYLON.serialize()
  70144. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70145. return FreeCameraGamepadInput;
  70146. }());
  70147. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70148. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70149. })(BABYLON || (BABYLON = {}));
  70150. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70151. var BABYLON;
  70152. (function (BABYLON) {
  70153. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70154. function ArcRotateCameraGamepadInput() {
  70155. this.gamepadRotationSensibility = 80;
  70156. this.gamepadMoveSensibility = 40;
  70157. }
  70158. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70159. var _this = this;
  70160. var manager = this.camera.getScene().gamepadManager;
  70161. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70162. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70163. // prioritize XBOX gamepads.
  70164. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70165. _this.gamepad = gamepad;
  70166. }
  70167. }
  70168. });
  70169. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70170. if (_this.gamepad === gamepad) {
  70171. _this.gamepad = null;
  70172. }
  70173. });
  70174. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70175. };
  70176. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70177. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70178. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70179. this.gamepad = null;
  70180. };
  70181. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70182. if (this.gamepad) {
  70183. var camera = this.camera;
  70184. var RSValues = this.gamepad.rightStick;
  70185. if (RSValues) {
  70186. if (RSValues.x != 0) {
  70187. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70188. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70189. camera.inertialAlphaOffset += normalizedRX;
  70190. }
  70191. }
  70192. if (RSValues.y != 0) {
  70193. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70194. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70195. camera.inertialBetaOffset += normalizedRY;
  70196. }
  70197. }
  70198. }
  70199. var LSValues = this.gamepad.leftStick;
  70200. if (LSValues && LSValues.y != 0) {
  70201. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70202. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70203. this.camera.inertialRadiusOffset -= normalizedLY;
  70204. }
  70205. }
  70206. }
  70207. };
  70208. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70209. return "ArcRotateCameraGamepadInput";
  70210. };
  70211. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70212. return "gamepad";
  70213. };
  70214. __decorate([
  70215. BABYLON.serialize()
  70216. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70217. __decorate([
  70218. BABYLON.serialize()
  70219. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70220. return ArcRotateCameraGamepadInput;
  70221. }());
  70222. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70223. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70224. })(BABYLON || (BABYLON = {}));
  70225. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70226. var BABYLON;
  70227. (function (BABYLON) {
  70228. var GamepadManager = /** @class */ (function () {
  70229. function GamepadManager(_scene) {
  70230. var _this = this;
  70231. this._scene = _scene;
  70232. this._babylonGamepads = [];
  70233. this._oneGamepadConnected = false;
  70234. this._isMonitoring = false;
  70235. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70236. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70237. this._gamepadEventSupported = false;
  70238. }
  70239. else {
  70240. this._gamepadEventSupported = 'GamepadEvent' in window;
  70241. this._gamepadSupport = (navigator.getGamepads ||
  70242. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70243. }
  70244. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70245. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70246. for (var i in _this._babylonGamepads) {
  70247. var gamepad = _this._babylonGamepads[i];
  70248. if (gamepad && gamepad._isConnected) {
  70249. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70250. }
  70251. }
  70252. });
  70253. this._onGamepadConnectedEvent = function (evt) {
  70254. var gamepad = evt.gamepad;
  70255. if (gamepad.index in _this._babylonGamepads) {
  70256. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70257. return;
  70258. }
  70259. }
  70260. var newGamepad;
  70261. if (_this._babylonGamepads[gamepad.index]) {
  70262. newGamepad = _this._babylonGamepads[gamepad.index];
  70263. newGamepad.browserGamepad = gamepad;
  70264. newGamepad._isConnected = true;
  70265. }
  70266. else {
  70267. newGamepad = _this._addNewGamepad(gamepad);
  70268. }
  70269. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70270. _this._startMonitoringGamepads();
  70271. };
  70272. this._onGamepadDisconnectedEvent = function (evt) {
  70273. var gamepad = evt.gamepad;
  70274. // Remove the gamepad from the list of gamepads to monitor.
  70275. for (var i in _this._babylonGamepads) {
  70276. if (_this._babylonGamepads[i].index === gamepad.index) {
  70277. var disconnectedGamepad = _this._babylonGamepads[i];
  70278. disconnectedGamepad._isConnected = false;
  70279. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70280. break;
  70281. }
  70282. }
  70283. };
  70284. if (this._gamepadSupport) {
  70285. //first add already-connected gamepads
  70286. this._updateGamepadObjects();
  70287. if (this._babylonGamepads.length) {
  70288. this._startMonitoringGamepads();
  70289. }
  70290. // Checking if the gamepad connected event is supported (like in Firefox)
  70291. if (this._gamepadEventSupported) {
  70292. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70293. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70294. }
  70295. else {
  70296. this._startMonitoringGamepads();
  70297. }
  70298. }
  70299. }
  70300. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70301. get: function () {
  70302. return this._babylonGamepads;
  70303. },
  70304. enumerable: true,
  70305. configurable: true
  70306. });
  70307. GamepadManager.prototype.getGamepadByType = function (type) {
  70308. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70309. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70310. var gamepad = _a[_i];
  70311. if (gamepad && gamepad.type === type) {
  70312. return gamepad;
  70313. }
  70314. }
  70315. return null;
  70316. };
  70317. GamepadManager.prototype.dispose = function () {
  70318. if (this._gamepadEventSupported) {
  70319. if (this._onGamepadConnectedEvent) {
  70320. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70321. }
  70322. if (this._onGamepadDisconnectedEvent) {
  70323. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70324. }
  70325. this._onGamepadConnectedEvent = null;
  70326. this._onGamepadDisconnectedEvent = null;
  70327. }
  70328. this._babylonGamepads.forEach(function (gamepad) {
  70329. gamepad.dispose();
  70330. });
  70331. this.onGamepadConnectedObservable.clear();
  70332. this.onGamepadDisconnectedObservable.clear();
  70333. this._oneGamepadConnected = false;
  70334. this._stopMonitoringGamepads();
  70335. this._babylonGamepads = [];
  70336. };
  70337. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70338. if (!this._oneGamepadConnected) {
  70339. this._oneGamepadConnected = true;
  70340. }
  70341. var newGamepad;
  70342. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70343. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70344. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70345. }
  70346. // if pose is supported, use the (WebVR) pose enabled controller
  70347. else if (gamepad.pose) {
  70348. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70349. }
  70350. else {
  70351. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70352. }
  70353. this._babylonGamepads[newGamepad.index] = newGamepad;
  70354. return newGamepad;
  70355. };
  70356. GamepadManager.prototype._startMonitoringGamepads = function () {
  70357. if (!this._isMonitoring) {
  70358. this._isMonitoring = true;
  70359. //back-comp
  70360. if (!this._scene) {
  70361. this._checkGamepadsStatus();
  70362. }
  70363. }
  70364. };
  70365. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70366. this._isMonitoring = false;
  70367. };
  70368. GamepadManager.prototype._checkGamepadsStatus = function () {
  70369. var _this = this;
  70370. // Hack to be compatible Chrome
  70371. this._updateGamepadObjects();
  70372. for (var i in this._babylonGamepads) {
  70373. var gamepad = this._babylonGamepads[i];
  70374. if (!gamepad || !gamepad.isConnected) {
  70375. continue;
  70376. }
  70377. gamepad.update();
  70378. }
  70379. if (this._isMonitoring && !this._scene) {
  70380. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70381. }
  70382. };
  70383. // This function is called only on Chrome, which does not properly support
  70384. // connection/disconnection events and forces you to recopy again the gamepad object
  70385. GamepadManager.prototype._updateGamepadObjects = function () {
  70386. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70387. for (var i = 0; i < gamepads.length; i++) {
  70388. var gamepad = gamepads[i];
  70389. if (gamepad) {
  70390. if (!this._babylonGamepads[gamepad.index]) {
  70391. var newGamepad = this._addNewGamepad(gamepad);
  70392. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70393. }
  70394. else {
  70395. // Forced to copy again this object for Chrome for unknown reason
  70396. this._babylonGamepads[i].browserGamepad = gamepad;
  70397. if (!this._babylonGamepads[i].isConnected) {
  70398. this._babylonGamepads[i]._isConnected = true;
  70399. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70400. }
  70401. }
  70402. }
  70403. }
  70404. };
  70405. return GamepadManager;
  70406. }());
  70407. BABYLON.GamepadManager = GamepadManager;
  70408. })(BABYLON || (BABYLON = {}));
  70409. //# sourceMappingURL=babylon.gamepadManager.js.map
  70410. var BABYLON;
  70411. (function (BABYLON) {
  70412. var StickValues = /** @class */ (function () {
  70413. function StickValues(x, y) {
  70414. this.x = x;
  70415. this.y = y;
  70416. }
  70417. return StickValues;
  70418. }());
  70419. BABYLON.StickValues = StickValues;
  70420. var Gamepad = /** @class */ (function () {
  70421. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70422. if (leftStickX === void 0) { leftStickX = 0; }
  70423. if (leftStickY === void 0) { leftStickY = 1; }
  70424. if (rightStickX === void 0) { rightStickX = 2; }
  70425. if (rightStickY === void 0) { rightStickY = 3; }
  70426. this.id = id;
  70427. this.index = index;
  70428. this.browserGamepad = browserGamepad;
  70429. this._isConnected = true;
  70430. this._invertLeftStickY = false;
  70431. this.type = Gamepad.GAMEPAD;
  70432. this._leftStickAxisX = leftStickX;
  70433. this._leftStickAxisY = leftStickY;
  70434. this._rightStickAxisX = rightStickX;
  70435. this._rightStickAxisY = rightStickY;
  70436. if (this.browserGamepad.axes.length >= 2) {
  70437. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70438. }
  70439. if (this.browserGamepad.axes.length >= 4) {
  70440. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70441. }
  70442. }
  70443. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70444. get: function () {
  70445. return this._isConnected;
  70446. },
  70447. enumerable: true,
  70448. configurable: true
  70449. });
  70450. Gamepad.prototype.onleftstickchanged = function (callback) {
  70451. this._onleftstickchanged = callback;
  70452. };
  70453. Gamepad.prototype.onrightstickchanged = function (callback) {
  70454. this._onrightstickchanged = callback;
  70455. };
  70456. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70457. get: function () {
  70458. return this._leftStick;
  70459. },
  70460. set: function (newValues) {
  70461. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70462. this._onleftstickchanged(newValues);
  70463. }
  70464. this._leftStick = newValues;
  70465. },
  70466. enumerable: true,
  70467. configurable: true
  70468. });
  70469. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70470. get: function () {
  70471. return this._rightStick;
  70472. },
  70473. set: function (newValues) {
  70474. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70475. this._onrightstickchanged(newValues);
  70476. }
  70477. this._rightStick = newValues;
  70478. },
  70479. enumerable: true,
  70480. configurable: true
  70481. });
  70482. Gamepad.prototype.update = function () {
  70483. if (this._leftStick) {
  70484. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70485. if (this._invertLeftStickY) {
  70486. this.leftStick.y *= -1;
  70487. }
  70488. }
  70489. if (this._rightStick) {
  70490. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70491. }
  70492. };
  70493. Gamepad.prototype.dispose = function () {
  70494. };
  70495. Gamepad.GAMEPAD = 0;
  70496. Gamepad.GENERIC = 1;
  70497. Gamepad.XBOX = 2;
  70498. Gamepad.POSE_ENABLED = 3;
  70499. return Gamepad;
  70500. }());
  70501. BABYLON.Gamepad = Gamepad;
  70502. var GenericPad = /** @class */ (function (_super) {
  70503. __extends(GenericPad, _super);
  70504. function GenericPad(id, index, browserGamepad) {
  70505. var _this = _super.call(this, id, index, browserGamepad) || this;
  70506. _this.onButtonDownObservable = new BABYLON.Observable();
  70507. _this.onButtonUpObservable = new BABYLON.Observable();
  70508. _this.type = Gamepad.GENERIC;
  70509. _this._buttons = new Array(browserGamepad.buttons.length);
  70510. return _this;
  70511. }
  70512. GenericPad.prototype.onbuttondown = function (callback) {
  70513. this._onbuttondown = callback;
  70514. };
  70515. GenericPad.prototype.onbuttonup = function (callback) {
  70516. this._onbuttonup = callback;
  70517. };
  70518. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70519. if (newValue !== currentValue) {
  70520. if (newValue === 1) {
  70521. if (this._onbuttondown) {
  70522. this._onbuttondown(buttonIndex);
  70523. }
  70524. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70525. }
  70526. if (newValue === 0) {
  70527. if (this._onbuttonup) {
  70528. this._onbuttonup(buttonIndex);
  70529. }
  70530. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70531. }
  70532. }
  70533. return newValue;
  70534. };
  70535. GenericPad.prototype.update = function () {
  70536. _super.prototype.update.call(this);
  70537. for (var index = 0; index < this._buttons.length; index++) {
  70538. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70539. }
  70540. };
  70541. GenericPad.prototype.dispose = function () {
  70542. _super.prototype.dispose.call(this);
  70543. this.onButtonDownObservable.clear();
  70544. this.onButtonUpObservable.clear();
  70545. };
  70546. return GenericPad;
  70547. }(Gamepad));
  70548. BABYLON.GenericPad = GenericPad;
  70549. })(BABYLON || (BABYLON = {}));
  70550. //# sourceMappingURL=babylon.gamepad.js.map
  70551. var BABYLON;
  70552. (function (BABYLON) {
  70553. /**
  70554. * Defines supported buttons for XBox360 compatible gamepads
  70555. */
  70556. var Xbox360Button;
  70557. (function (Xbox360Button) {
  70558. /** A */
  70559. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70560. /** B */
  70561. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70562. /** X */
  70563. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70564. /** Y */
  70565. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70566. /** Start */
  70567. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70568. /** Back */
  70569. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70570. /** Left button */
  70571. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70572. /** Right button */
  70573. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70574. /** Left stick */
  70575. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70576. /** Right stick */
  70577. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70578. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70579. /** Defines values for XBox360 DPad */
  70580. var Xbox360Dpad;
  70581. (function (Xbox360Dpad) {
  70582. /** Up */
  70583. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70584. /** Down */
  70585. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70586. /** Left */
  70587. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70588. /** Right */
  70589. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70590. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70591. /**
  70592. * Defines a XBox360 gamepad
  70593. */
  70594. var Xbox360Pad = /** @class */ (function (_super) {
  70595. __extends(Xbox360Pad, _super);
  70596. /**
  70597. * Creates a new XBox360 gamepad object
  70598. * @param id defines the id of this gamepad
  70599. * @param index defines its index
  70600. * @param gamepad defines the internal HTML gamepad object
  70601. * @param xboxOne defines if it is a XBox One gamepad
  70602. */
  70603. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70604. if (xboxOne === void 0) { xboxOne = false; }
  70605. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70606. _this._leftTrigger = 0;
  70607. _this._rightTrigger = 0;
  70608. /** Observable raised when a button is pressed */
  70609. _this.onButtonDownObservable = new BABYLON.Observable();
  70610. /** Observable raised when a button is released */
  70611. _this.onButtonUpObservable = new BABYLON.Observable();
  70612. /** Observable raised when a pad is pressed */
  70613. _this.onPadDownObservable = new BABYLON.Observable();
  70614. /** Observable raised when a pad is released */
  70615. _this.onPadUpObservable = new BABYLON.Observable();
  70616. _this._buttonA = 0;
  70617. _this._buttonB = 0;
  70618. _this._buttonX = 0;
  70619. _this._buttonY = 0;
  70620. _this._buttonBack = 0;
  70621. _this._buttonStart = 0;
  70622. _this._buttonLB = 0;
  70623. _this._buttonRB = 0;
  70624. _this._buttonLeftStick = 0;
  70625. _this._buttonRightStick = 0;
  70626. _this._dPadUp = 0;
  70627. _this._dPadDown = 0;
  70628. _this._dPadLeft = 0;
  70629. _this._dPadRight = 0;
  70630. _this._isXboxOnePad = false;
  70631. _this.type = BABYLON.Gamepad.XBOX;
  70632. _this._isXboxOnePad = xboxOne;
  70633. return _this;
  70634. }
  70635. /**
  70636. * Defines the callback to call when left trigger is pressed
  70637. * @param callback defines the callback to use
  70638. */
  70639. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70640. this._onlefttriggerchanged = callback;
  70641. };
  70642. /**
  70643. * Defines the callback to call when right trigger is pressed
  70644. * @param callback defines the callback to use
  70645. */
  70646. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70647. this._onrighttriggerchanged = callback;
  70648. };
  70649. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70650. /**
  70651. * Gets or sets left trigger value
  70652. */
  70653. get: function () {
  70654. return this._leftTrigger;
  70655. },
  70656. set: function (newValue) {
  70657. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70658. this._onlefttriggerchanged(newValue);
  70659. }
  70660. this._leftTrigger = newValue;
  70661. },
  70662. enumerable: true,
  70663. configurable: true
  70664. });
  70665. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70666. /**
  70667. * Gets or sets right trigger value
  70668. */
  70669. get: function () {
  70670. return this._rightTrigger;
  70671. },
  70672. set: function (newValue) {
  70673. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70674. this._onrighttriggerchanged(newValue);
  70675. }
  70676. this._rightTrigger = newValue;
  70677. },
  70678. enumerable: true,
  70679. configurable: true
  70680. });
  70681. /**
  70682. * Defines the callback to call when a button is pressed
  70683. * @param callback defines the callback to use
  70684. */
  70685. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70686. this._onbuttondown = callback;
  70687. };
  70688. /**
  70689. * Defines the callback to call when a button is released
  70690. * @param callback defines the callback to use
  70691. */
  70692. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70693. this._onbuttonup = callback;
  70694. };
  70695. /**
  70696. * Defines the callback to call when a pad is pressed
  70697. * @param callback defines the callback to use
  70698. */
  70699. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70700. this._ondpaddown = callback;
  70701. };
  70702. /**
  70703. * Defines the callback to call when a pad is released
  70704. * @param callback defines the callback to use
  70705. */
  70706. Xbox360Pad.prototype.ondpadup = function (callback) {
  70707. this._ondpadup = callback;
  70708. };
  70709. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70710. if (newValue !== currentValue) {
  70711. if (newValue === 1) {
  70712. if (this._onbuttondown) {
  70713. this._onbuttondown(buttonType);
  70714. }
  70715. this.onButtonDownObservable.notifyObservers(buttonType);
  70716. }
  70717. if (newValue === 0) {
  70718. if (this._onbuttonup) {
  70719. this._onbuttonup(buttonType);
  70720. }
  70721. this.onButtonUpObservable.notifyObservers(buttonType);
  70722. }
  70723. }
  70724. return newValue;
  70725. };
  70726. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70727. if (newValue !== currentValue) {
  70728. if (newValue === 1) {
  70729. if (this._ondpaddown) {
  70730. this._ondpaddown(buttonType);
  70731. }
  70732. this.onPadDownObservable.notifyObservers(buttonType);
  70733. }
  70734. if (newValue === 0) {
  70735. if (this._ondpadup) {
  70736. this._ondpadup(buttonType);
  70737. }
  70738. this.onPadUpObservable.notifyObservers(buttonType);
  70739. }
  70740. }
  70741. return newValue;
  70742. };
  70743. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70744. /** Gets or sets value of A button */
  70745. get: function () {
  70746. return this._buttonA;
  70747. },
  70748. set: function (value) {
  70749. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70750. },
  70751. enumerable: true,
  70752. configurable: true
  70753. });
  70754. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70755. /** Gets or sets value of B button */
  70756. get: function () {
  70757. return this._buttonB;
  70758. },
  70759. set: function (value) {
  70760. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70761. },
  70762. enumerable: true,
  70763. configurable: true
  70764. });
  70765. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70766. /** Gets or sets value of X button */
  70767. get: function () {
  70768. return this._buttonX;
  70769. },
  70770. set: function (value) {
  70771. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70772. },
  70773. enumerable: true,
  70774. configurable: true
  70775. });
  70776. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70777. /** Gets or sets value of Y button */
  70778. get: function () {
  70779. return this._buttonY;
  70780. },
  70781. set: function (value) {
  70782. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70783. },
  70784. enumerable: true,
  70785. configurable: true
  70786. });
  70787. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70788. /** Gets or sets value of Start button */
  70789. get: function () {
  70790. return this._buttonStart;
  70791. },
  70792. set: function (value) {
  70793. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70794. },
  70795. enumerable: true,
  70796. configurable: true
  70797. });
  70798. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70799. /** Gets or sets value of Back button */
  70800. get: function () {
  70801. return this._buttonBack;
  70802. },
  70803. set: function (value) {
  70804. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70805. },
  70806. enumerable: true,
  70807. configurable: true
  70808. });
  70809. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70810. /** Gets or sets value of Left button */
  70811. get: function () {
  70812. return this._buttonLB;
  70813. },
  70814. set: function (value) {
  70815. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70816. },
  70817. enumerable: true,
  70818. configurable: true
  70819. });
  70820. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70821. /** Gets or sets value of Right button */
  70822. get: function () {
  70823. return this._buttonRB;
  70824. },
  70825. set: function (value) {
  70826. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70827. },
  70828. enumerable: true,
  70829. configurable: true
  70830. });
  70831. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70832. /** Gets or sets value of left stick */
  70833. get: function () {
  70834. return this._buttonLeftStick;
  70835. },
  70836. set: function (value) {
  70837. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70838. },
  70839. enumerable: true,
  70840. configurable: true
  70841. });
  70842. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70843. /** Gets or sets value of right stick */
  70844. get: function () {
  70845. return this._buttonRightStick;
  70846. },
  70847. set: function (value) {
  70848. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70849. },
  70850. enumerable: true,
  70851. configurable: true
  70852. });
  70853. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70854. /** Gets or sets value of DPad up */
  70855. get: function () {
  70856. return this._dPadUp;
  70857. },
  70858. set: function (value) {
  70859. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70860. },
  70861. enumerable: true,
  70862. configurable: true
  70863. });
  70864. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70865. /** Gets or sets value of DPad down */
  70866. get: function () {
  70867. return this._dPadDown;
  70868. },
  70869. set: function (value) {
  70870. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70871. },
  70872. enumerable: true,
  70873. configurable: true
  70874. });
  70875. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70876. /** Gets or sets value of DPad left */
  70877. get: function () {
  70878. return this._dPadLeft;
  70879. },
  70880. set: function (value) {
  70881. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70882. },
  70883. enumerable: true,
  70884. configurable: true
  70885. });
  70886. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70887. /** Gets or sets value of DPad right */
  70888. get: function () {
  70889. return this._dPadRight;
  70890. },
  70891. set: function (value) {
  70892. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70893. },
  70894. enumerable: true,
  70895. configurable: true
  70896. });
  70897. /**
  70898. * Force the gamepad to synchronize with device values
  70899. */
  70900. Xbox360Pad.prototype.update = function () {
  70901. _super.prototype.update.call(this);
  70902. if (this._isXboxOnePad) {
  70903. this.buttonA = this.browserGamepad.buttons[0].value;
  70904. this.buttonB = this.browserGamepad.buttons[1].value;
  70905. this.buttonX = this.browserGamepad.buttons[2].value;
  70906. this.buttonY = this.browserGamepad.buttons[3].value;
  70907. this.buttonLB = this.browserGamepad.buttons[4].value;
  70908. this.buttonRB = this.browserGamepad.buttons[5].value;
  70909. this.leftTrigger = this.browserGamepad.axes[2];
  70910. this.rightTrigger = this.browserGamepad.axes[5];
  70911. this.buttonBack = this.browserGamepad.buttons[9].value;
  70912. this.buttonStart = this.browserGamepad.buttons[8].value;
  70913. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70914. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70915. this.dPadUp = this.browserGamepad.buttons[11].value;
  70916. this.dPadDown = this.browserGamepad.buttons[12].value;
  70917. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70918. this.dPadRight = this.browserGamepad.buttons[14].value;
  70919. }
  70920. else {
  70921. this.buttonA = this.browserGamepad.buttons[0].value;
  70922. this.buttonB = this.browserGamepad.buttons[1].value;
  70923. this.buttonX = this.browserGamepad.buttons[2].value;
  70924. this.buttonY = this.browserGamepad.buttons[3].value;
  70925. this.buttonLB = this.browserGamepad.buttons[4].value;
  70926. this.buttonRB = this.browserGamepad.buttons[5].value;
  70927. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70928. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70929. this.buttonBack = this.browserGamepad.buttons[8].value;
  70930. this.buttonStart = this.browserGamepad.buttons[9].value;
  70931. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70932. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70933. this.dPadUp = this.browserGamepad.buttons[12].value;
  70934. this.dPadDown = this.browserGamepad.buttons[13].value;
  70935. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70936. this.dPadRight = this.browserGamepad.buttons[15].value;
  70937. }
  70938. };
  70939. Xbox360Pad.prototype.dispose = function () {
  70940. _super.prototype.dispose.call(this);
  70941. this.onButtonDownObservable.clear();
  70942. this.onButtonUpObservable.clear();
  70943. this.onPadDownObservable.clear();
  70944. this.onPadUpObservable.clear();
  70945. };
  70946. return Xbox360Pad;
  70947. }(BABYLON.Gamepad));
  70948. BABYLON.Xbox360Pad = Xbox360Pad;
  70949. })(BABYLON || (BABYLON = {}));
  70950. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70951. var BABYLON;
  70952. (function (BABYLON) {
  70953. /**
  70954. * Defines the types of pose enabled controllers that are supported
  70955. */
  70956. var PoseEnabledControllerType;
  70957. (function (PoseEnabledControllerType) {
  70958. /**
  70959. * HTC Vive
  70960. */
  70961. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70962. /**
  70963. * Oculus Rift
  70964. */
  70965. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70966. /**
  70967. * Windows mixed reality
  70968. */
  70969. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70970. /**
  70971. * Samsung gear VR
  70972. */
  70973. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70974. /**
  70975. * Google Daydream
  70976. */
  70977. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70978. /**
  70979. * Generic
  70980. */
  70981. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70982. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70983. /**
  70984. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70985. */
  70986. var PoseEnabledControllerHelper = /** @class */ (function () {
  70987. function PoseEnabledControllerHelper() {
  70988. }
  70989. /**
  70990. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70991. * @param vrGamepad the gamepad to initialized
  70992. * @returns a vr controller of the type the gamepad identified as
  70993. */
  70994. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70995. // Oculus Touch
  70996. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70997. return new BABYLON.OculusTouchController(vrGamepad);
  70998. }
  70999. // Windows Mixed Reality controllers
  71000. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71001. return new BABYLON.WindowsMotionController(vrGamepad);
  71002. }
  71003. // HTC Vive
  71004. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71005. return new BABYLON.ViveController(vrGamepad);
  71006. }
  71007. // Samsung/Oculus Gear VR
  71008. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  71009. return new BABYLON.GearVRController(vrGamepad);
  71010. }
  71011. // Google Daydream
  71012. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71013. return new BABYLON.DaydreamController(vrGamepad);
  71014. }
  71015. // Generic
  71016. else {
  71017. return new BABYLON.GenericController(vrGamepad);
  71018. }
  71019. };
  71020. return PoseEnabledControllerHelper;
  71021. }());
  71022. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71023. /**
  71024. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71025. */
  71026. var PoseEnabledController = /** @class */ (function (_super) {
  71027. __extends(PoseEnabledController, _super);
  71028. /**
  71029. * Creates a new PoseEnabledController from a gamepad
  71030. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71031. */
  71032. function PoseEnabledController(browserGamepad) {
  71033. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71034. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71035. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71036. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71037. /**
  71038. * The device position in babylon space
  71039. */
  71040. _this.devicePosition = BABYLON.Vector3.Zero();
  71041. /**
  71042. * The device rotation in babylon space
  71043. */
  71044. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71045. /**
  71046. * The scale factor of the device in babylon space
  71047. */
  71048. _this.deviceScaleFactor = 1;
  71049. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71050. /**
  71051. * Internal, matrix used to convert room space to babylon space
  71052. */
  71053. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71054. /**
  71055. * Node to be used when casting a ray from the controller
  71056. */
  71057. _this._pointingPoseNode = null;
  71058. _this._workingMatrix = BABYLON.Matrix.Identity();
  71059. /**
  71060. * @hidden
  71061. */
  71062. _this._meshAttachedObservable = new BABYLON.Observable();
  71063. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71064. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71065. _this.position = BABYLON.Vector3.Zero();
  71066. _this.rotationQuaternion = new BABYLON.Quaternion();
  71067. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71068. _this._calculatedRotation = new BABYLON.Quaternion();
  71069. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71070. return _this;
  71071. }
  71072. /**
  71073. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71074. */
  71075. PoseEnabledController.prototype.update = function () {
  71076. _super.prototype.update.call(this);
  71077. var pose = this.browserGamepad.pose;
  71078. this.updateFromDevice(pose);
  71079. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71080. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71081. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71082. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71083. if (this._mesh) {
  71084. this._mesh.position.copyFrom(this.devicePosition);
  71085. if (this._mesh.rotationQuaternion) {
  71086. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71087. }
  71088. }
  71089. };
  71090. /**
  71091. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71092. * @param poseData raw pose fromthe device
  71093. */
  71094. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71095. if (poseData) {
  71096. this.rawPose = poseData;
  71097. if (poseData.position) {
  71098. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71099. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71100. this._deviceRoomPosition.z *= -1;
  71101. }
  71102. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71103. this._calculatedPosition.addInPlace(this.position);
  71104. }
  71105. var pose = this.rawPose;
  71106. if (poseData.orientation && pose.orientation) {
  71107. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71108. if (this._mesh) {
  71109. if (this._mesh.getScene().useRightHandedSystem) {
  71110. this._deviceRoomRotationQuaternion.z *= -1;
  71111. this._deviceRoomRotationQuaternion.w *= -1;
  71112. }
  71113. else {
  71114. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71115. }
  71116. }
  71117. // if the camera is set, rotate to the camera's rotation
  71118. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71119. }
  71120. }
  71121. };
  71122. /**
  71123. * Attaches a mesh to the controller
  71124. * @param mesh the mesh to be attached
  71125. */
  71126. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71127. if (this._mesh) {
  71128. this._mesh.parent = null;
  71129. }
  71130. this._mesh = mesh;
  71131. if (this._poseControlledCamera) {
  71132. this._mesh.parent = this._poseControlledCamera;
  71133. }
  71134. if (!this._mesh.rotationQuaternion) {
  71135. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71136. }
  71137. this._meshAttachedObservable.notifyObservers(mesh);
  71138. };
  71139. /**
  71140. * Attaches the controllers mesh to a camera
  71141. * @param camera the camera the mesh should be attached to
  71142. */
  71143. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71144. this._poseControlledCamera = camera;
  71145. if (this._mesh) {
  71146. this._mesh.parent = this._poseControlledCamera;
  71147. }
  71148. };
  71149. /**
  71150. * Disposes of the controller
  71151. */
  71152. PoseEnabledController.prototype.dispose = function () {
  71153. if (this._mesh) {
  71154. this._mesh.dispose();
  71155. }
  71156. this._mesh = null;
  71157. _super.prototype.dispose.call(this);
  71158. };
  71159. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71160. /**
  71161. * The mesh that is attached to the controller
  71162. */
  71163. get: function () {
  71164. return this._mesh;
  71165. },
  71166. enumerable: true,
  71167. configurable: true
  71168. });
  71169. /**
  71170. * Gets the ray of the controller in the direction the controller is pointing
  71171. * @param length the length the resulting ray should be
  71172. * @returns a ray in the direction the controller is pointing
  71173. */
  71174. PoseEnabledController.prototype.getForwardRay = function (length) {
  71175. if (length === void 0) { length = 100; }
  71176. if (!this.mesh) {
  71177. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71178. }
  71179. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71180. var origin = m.getTranslation();
  71181. var forward = new BABYLON.Vector3(0, 0, -1);
  71182. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71183. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71184. return new BABYLON.Ray(origin, direction, length);
  71185. };
  71186. /**
  71187. * Name of the child mesh that can be used to cast a ray from the controller
  71188. */
  71189. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71190. return PoseEnabledController;
  71191. }(BABYLON.Gamepad));
  71192. BABYLON.PoseEnabledController = PoseEnabledController;
  71193. })(BABYLON || (BABYLON = {}));
  71194. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71195. var BABYLON;
  71196. (function (BABYLON) {
  71197. /**
  71198. * Defines the WebVRController object that represents controllers tracked in 3D space
  71199. */
  71200. var WebVRController = /** @class */ (function (_super) {
  71201. __extends(WebVRController, _super);
  71202. /**
  71203. * Creates a new WebVRController from a gamepad
  71204. * @param vrGamepad the gamepad that the WebVRController should be created from
  71205. */
  71206. function WebVRController(vrGamepad) {
  71207. var _this = _super.call(this, vrGamepad) || this;
  71208. // Observables
  71209. /**
  71210. * Fired when the trigger state has changed
  71211. */
  71212. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71213. /**
  71214. * Fired when the main button state has changed
  71215. */
  71216. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71217. /**
  71218. * Fired when the secondary button state has changed
  71219. */
  71220. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71221. /**
  71222. * Fired when the pad state has changed
  71223. */
  71224. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71225. /**
  71226. * Fired when controllers stick values have changed
  71227. */
  71228. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71229. /**
  71230. * X and Y axis corrisponding to the controllers joystick
  71231. */
  71232. _this.pad = { x: 0, y: 0 };
  71233. // avoid GC, store state in a tmp object
  71234. _this._changes = {
  71235. pressChanged: false,
  71236. touchChanged: false,
  71237. valueChanged: false,
  71238. changed: false
  71239. };
  71240. _this._buttons = new Array(vrGamepad.buttons.length);
  71241. _this.hand = vrGamepad.hand;
  71242. return _this;
  71243. }
  71244. /**
  71245. * Fired when a controller button's state has changed
  71246. * @param callback the callback containing the button that was modified
  71247. */
  71248. WebVRController.prototype.onButtonStateChange = function (callback) {
  71249. this._onButtonStateChange = callback;
  71250. };
  71251. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71252. /**
  71253. * The default controller model for the controller
  71254. */
  71255. get: function () {
  71256. return this._defaultModel;
  71257. },
  71258. enumerable: true,
  71259. configurable: true
  71260. });
  71261. /**
  71262. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71263. */
  71264. WebVRController.prototype.update = function () {
  71265. _super.prototype.update.call(this);
  71266. for (var index = 0; index < this._buttons.length; index++) {
  71267. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71268. }
  71269. ;
  71270. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71271. this.pad.x = this.leftStick.x;
  71272. this.pad.y = this.leftStick.y;
  71273. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71274. }
  71275. };
  71276. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71277. if (!newState) {
  71278. newState = {
  71279. pressed: false,
  71280. touched: false,
  71281. value: 0
  71282. };
  71283. }
  71284. if (!currentState) {
  71285. this._buttons[buttonIndex] = {
  71286. pressed: newState.pressed,
  71287. touched: newState.touched,
  71288. value: newState.value
  71289. };
  71290. return;
  71291. }
  71292. this._checkChanges(newState, currentState);
  71293. if (this._changes.changed) {
  71294. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71295. this._handleButtonChange(buttonIndex, newState, this._changes);
  71296. }
  71297. this._buttons[buttonIndex].pressed = newState.pressed;
  71298. this._buttons[buttonIndex].touched = newState.touched;
  71299. // oculus triggers are never 0, thou not touched.
  71300. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71301. };
  71302. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71303. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71304. this._changes.touchChanged = newState.touched !== currentState.touched;
  71305. this._changes.valueChanged = newState.value !== currentState.value;
  71306. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71307. return this._changes;
  71308. };
  71309. /**
  71310. * Disposes of th webVRCOntroller
  71311. */
  71312. WebVRController.prototype.dispose = function () {
  71313. _super.prototype.dispose.call(this);
  71314. this.onTriggerStateChangedObservable.clear();
  71315. this.onMainButtonStateChangedObservable.clear();
  71316. this.onSecondaryButtonStateChangedObservable.clear();
  71317. this.onPadStateChangedObservable.clear();
  71318. this.onPadValuesChangedObservable.clear();
  71319. };
  71320. return WebVRController;
  71321. }(BABYLON.PoseEnabledController));
  71322. BABYLON.WebVRController = WebVRController;
  71323. })(BABYLON || (BABYLON = {}));
  71324. //# sourceMappingURL=babylon.webVRController.js.map
  71325. var BABYLON;
  71326. (function (BABYLON) {
  71327. /**
  71328. * Oculus Touch Controller
  71329. */
  71330. var OculusTouchController = /** @class */ (function (_super) {
  71331. __extends(OculusTouchController, _super);
  71332. /**
  71333. * Creates a new OculusTouchController from a gamepad
  71334. * @param vrGamepad the gamepad that the controller should be created from
  71335. */
  71336. function OculusTouchController(vrGamepad) {
  71337. var _this = _super.call(this, vrGamepad) || this;
  71338. /**
  71339. * Fired when the secondary trigger on this controller is modified
  71340. */
  71341. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71342. /**
  71343. * Fired when the thumb rest on this controller is modified
  71344. */
  71345. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71346. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71347. return _this;
  71348. }
  71349. /**
  71350. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71351. * @param scene scene in which to add meshes
  71352. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71353. */
  71354. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71355. var _this = this;
  71356. var meshName;
  71357. // Hand
  71358. if (this.hand === 'left') {
  71359. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71360. }
  71361. else { // Right is the default if no hand is specified
  71362. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71363. }
  71364. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71365. /*
  71366. Parent Mesh name: oculus_touch_left
  71367. - body
  71368. - trigger
  71369. - thumbstick
  71370. - grip
  71371. - button_y
  71372. - button_x
  71373. - button_enter
  71374. */
  71375. _this._defaultModel = newMeshes[1];
  71376. _this.attachToMesh(_this._defaultModel);
  71377. if (meshLoaded) {
  71378. meshLoaded(_this._defaultModel);
  71379. }
  71380. });
  71381. };
  71382. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71383. /**
  71384. * Fired when the A button on this controller is modified
  71385. */
  71386. get: function () {
  71387. if (this.hand === 'right') {
  71388. return this.onMainButtonStateChangedObservable;
  71389. }
  71390. else {
  71391. throw new Error('No A button on left hand');
  71392. }
  71393. },
  71394. enumerable: true,
  71395. configurable: true
  71396. });
  71397. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71398. /**
  71399. * Fired when the B button on this controller is modified
  71400. */
  71401. get: function () {
  71402. if (this.hand === 'right') {
  71403. return this.onSecondaryButtonStateChangedObservable;
  71404. }
  71405. else {
  71406. throw new Error('No B button on left hand');
  71407. }
  71408. },
  71409. enumerable: true,
  71410. configurable: true
  71411. });
  71412. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71413. /**
  71414. * Fired when the X button on this controller is modified
  71415. */
  71416. get: function () {
  71417. if (this.hand === 'left') {
  71418. return this.onMainButtonStateChangedObservable;
  71419. }
  71420. else {
  71421. throw new Error('No X button on right hand');
  71422. }
  71423. },
  71424. enumerable: true,
  71425. configurable: true
  71426. });
  71427. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71428. /**
  71429. * Fired when the Y button on this controller is modified
  71430. */
  71431. get: function () {
  71432. if (this.hand === 'left') {
  71433. return this.onSecondaryButtonStateChangedObservable;
  71434. }
  71435. else {
  71436. throw new Error('No Y button on right hand');
  71437. }
  71438. },
  71439. enumerable: true,
  71440. configurable: true
  71441. });
  71442. /**
  71443. * Called once for each button that changed state since the last frame
  71444. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71445. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71446. * 2) secondary trigger (same)
  71447. * 3) A (right) X (left), touch, pressed = value
  71448. * 4) B / Y
  71449. * 5) thumb rest
  71450. * @param buttonIdx Which button index changed
  71451. * @param state New state of the button
  71452. * @param changes Which properties on the state changed since last frame
  71453. */
  71454. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71455. var notifyObject = state; //{ state: state, changes: changes };
  71456. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71457. switch (buttonIdx) {
  71458. case 0:
  71459. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71460. return;
  71461. case 1: // index trigger
  71462. if (this._defaultModel) {
  71463. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71464. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71465. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71466. }
  71467. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71468. return;
  71469. case 2: // secondary trigger
  71470. if (this._defaultModel) {
  71471. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71472. }
  71473. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71474. return;
  71475. case 3:
  71476. if (this._defaultModel) {
  71477. if (notifyObject.pressed) {
  71478. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71479. }
  71480. else {
  71481. (this._defaultModel.getChildren()[1]).position.y = 0;
  71482. }
  71483. }
  71484. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71485. return;
  71486. case 4:
  71487. if (this._defaultModel) {
  71488. if (notifyObject.pressed) {
  71489. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71490. }
  71491. else {
  71492. (this._defaultModel.getChildren()[2]).position.y = 0;
  71493. }
  71494. }
  71495. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71496. return;
  71497. case 5:
  71498. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71499. return;
  71500. }
  71501. };
  71502. /**
  71503. * Base Url for the controller model.
  71504. */
  71505. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71506. /**
  71507. * File name for the left controller model.
  71508. */
  71509. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71510. /**
  71511. * File name for the right controller model.
  71512. */
  71513. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71514. return OculusTouchController;
  71515. }(BABYLON.WebVRController));
  71516. BABYLON.OculusTouchController = OculusTouchController;
  71517. })(BABYLON || (BABYLON = {}));
  71518. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71519. var BABYLON;
  71520. (function (BABYLON) {
  71521. /**
  71522. * Vive Controller
  71523. */
  71524. var ViveController = /** @class */ (function (_super) {
  71525. __extends(ViveController, _super);
  71526. /**
  71527. * Creates a new ViveController from a gamepad
  71528. * @param vrGamepad the gamepad that the controller should be created from
  71529. */
  71530. function ViveController(vrGamepad) {
  71531. var _this = _super.call(this, vrGamepad) || this;
  71532. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71533. _this._invertLeftStickY = true;
  71534. return _this;
  71535. }
  71536. /**
  71537. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71538. * @param scene scene in which to add meshes
  71539. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71540. */
  71541. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71542. var _this = this;
  71543. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71544. /*
  71545. Parent Mesh name: ViveWand
  71546. - body
  71547. - r_gripper
  71548. - l_gripper
  71549. - menu_button
  71550. - system_button
  71551. - trackpad
  71552. - trigger
  71553. - LED
  71554. */
  71555. _this._defaultModel = newMeshes[1];
  71556. _this.attachToMesh(_this._defaultModel);
  71557. if (meshLoaded) {
  71558. meshLoaded(_this._defaultModel);
  71559. }
  71560. });
  71561. };
  71562. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71563. /**
  71564. * Fired when the left button on this controller is modified
  71565. */
  71566. get: function () {
  71567. return this.onMainButtonStateChangedObservable;
  71568. },
  71569. enumerable: true,
  71570. configurable: true
  71571. });
  71572. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71573. /**
  71574. * Fired when the right button on this controller is modified
  71575. */
  71576. get: function () {
  71577. return this.onMainButtonStateChangedObservable;
  71578. },
  71579. enumerable: true,
  71580. configurable: true
  71581. });
  71582. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71583. /**
  71584. * Fired when the menu button on this controller is modified
  71585. */
  71586. get: function () {
  71587. return this.onSecondaryButtonStateChangedObservable;
  71588. },
  71589. enumerable: true,
  71590. configurable: true
  71591. });
  71592. /**
  71593. * Called once for each button that changed state since the last frame
  71594. * Vive mapping:
  71595. * 0: touchpad
  71596. * 1: trigger
  71597. * 2: left AND right buttons
  71598. * 3: menu button
  71599. * @param buttonIdx Which button index changed
  71600. * @param state New state of the button
  71601. * @param changes Which properties on the state changed since last frame
  71602. */
  71603. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71604. var notifyObject = state; //{ state: state, changes: changes };
  71605. switch (buttonIdx) {
  71606. case 0:
  71607. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71608. return;
  71609. case 1: // index trigger
  71610. if (this._defaultModel) {
  71611. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71612. }
  71613. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71614. return;
  71615. case 2: // left AND right button
  71616. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71617. return;
  71618. case 3:
  71619. if (this._defaultModel) {
  71620. if (notifyObject.pressed) {
  71621. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71622. }
  71623. else {
  71624. (this._defaultModel.getChildren()[2]).position.y = 0;
  71625. }
  71626. }
  71627. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71628. return;
  71629. }
  71630. };
  71631. /**
  71632. * Base Url for the controller model.
  71633. */
  71634. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71635. /**
  71636. * File name for the controller model.
  71637. */
  71638. ViveController.MODEL_FILENAME = 'wand.babylon';
  71639. return ViveController;
  71640. }(BABYLON.WebVRController));
  71641. BABYLON.ViveController = ViveController;
  71642. })(BABYLON || (BABYLON = {}));
  71643. //# sourceMappingURL=babylon.viveController.js.map
  71644. var BABYLON;
  71645. (function (BABYLON) {
  71646. /**
  71647. * Generic Controller
  71648. */
  71649. var GenericController = /** @class */ (function (_super) {
  71650. __extends(GenericController, _super);
  71651. /**
  71652. * Creates a new GenericController from a gamepad
  71653. * @param vrGamepad the gamepad that the controller should be created from
  71654. */
  71655. function GenericController(vrGamepad) {
  71656. return _super.call(this, vrGamepad) || this;
  71657. }
  71658. /**
  71659. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71660. * @param scene scene in which to add meshes
  71661. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71662. */
  71663. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71664. var _this = this;
  71665. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71666. _this._defaultModel = newMeshes[1];
  71667. _this.attachToMesh(_this._defaultModel);
  71668. if (meshLoaded) {
  71669. meshLoaded(_this._defaultModel);
  71670. }
  71671. });
  71672. };
  71673. /**
  71674. * Called once for each button that changed state since the last frame
  71675. * @param buttonIdx Which button index changed
  71676. * @param state New state of the button
  71677. * @param changes Which properties on the state changed since last frame
  71678. */
  71679. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71680. console.log("Button id: " + buttonIdx + "state: ");
  71681. console.dir(state);
  71682. };
  71683. /**
  71684. * Base Url for the controller model.
  71685. */
  71686. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71687. /**
  71688. * File name for the controller model.
  71689. */
  71690. GenericController.MODEL_FILENAME = 'generic.babylon';
  71691. return GenericController;
  71692. }(BABYLON.WebVRController));
  71693. BABYLON.GenericController = GenericController;
  71694. })(BABYLON || (BABYLON = {}));
  71695. //# sourceMappingURL=babylon.genericController.js.map
  71696. var BABYLON;
  71697. (function (BABYLON) {
  71698. /**
  71699. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71700. */
  71701. var LoadedMeshInfo = /** @class */ (function () {
  71702. function LoadedMeshInfo() {
  71703. /**
  71704. * Map of the button meshes contained in the controller
  71705. */
  71706. this.buttonMeshes = {};
  71707. /**
  71708. * Map of the axis meshes contained in the controller
  71709. */
  71710. this.axisMeshes = {};
  71711. }
  71712. return LoadedMeshInfo;
  71713. }());
  71714. /**
  71715. * Defines the WindowsMotionController object that the state of the windows motion controller
  71716. */
  71717. var WindowsMotionController = /** @class */ (function (_super) {
  71718. __extends(WindowsMotionController, _super);
  71719. /**
  71720. * Creates a new WindowsMotionController from a gamepad
  71721. * @param vrGamepad the gamepad that the controller should be created from
  71722. */
  71723. function WindowsMotionController(vrGamepad) {
  71724. var _this = _super.call(this, vrGamepad) || this;
  71725. _this._mapping = {
  71726. // Semantic button names
  71727. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71728. // A mapping of the button name to glTF model node name
  71729. // that should be transformed by button value.
  71730. buttonMeshNames: {
  71731. 'trigger': 'SELECT',
  71732. 'menu': 'MENU',
  71733. 'grip': 'GRASP',
  71734. 'thumbstick': 'THUMBSTICK_PRESS',
  71735. 'trackpad': 'TOUCHPAD_PRESS'
  71736. },
  71737. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71738. buttonObservableNames: {
  71739. 'trigger': 'onTriggerStateChangedObservable',
  71740. 'menu': 'onSecondaryButtonStateChangedObservable',
  71741. 'grip': 'onMainButtonStateChangedObservable',
  71742. 'thumbstick': 'onPadStateChangedObservable',
  71743. 'trackpad': 'onTrackpadChangedObservable'
  71744. },
  71745. // A mapping of the axis name to glTF model node name
  71746. // that should be transformed by axis value.
  71747. // This array mirrors the browserGamepad.axes array, such that
  71748. // the mesh corresponding to axis 0 is in this array index 0.
  71749. axisMeshNames: [
  71750. 'THUMBSTICK_X',
  71751. 'THUMBSTICK_Y',
  71752. 'TOUCHPAD_TOUCH_X',
  71753. 'TOUCHPAD_TOUCH_Y'
  71754. ],
  71755. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71756. };
  71757. /**
  71758. * Fired when the trackpad on this controller is clicked
  71759. */
  71760. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71761. /**
  71762. * Fired when the trackpad on this controller is modified
  71763. */
  71764. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71765. /**
  71766. * The current x and y values of this controller's trackpad
  71767. */
  71768. _this.trackpad = { x: 0, y: 0 };
  71769. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71770. _this._loadedMeshInfo = null;
  71771. return _this;
  71772. }
  71773. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71774. /**
  71775. * Fired when the trigger on this controller is modified
  71776. */
  71777. get: function () {
  71778. return this.onTriggerStateChangedObservable;
  71779. },
  71780. enumerable: true,
  71781. configurable: true
  71782. });
  71783. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71784. /**
  71785. * Fired when the menu button on this controller is modified
  71786. */
  71787. get: function () {
  71788. return this.onSecondaryButtonStateChangedObservable;
  71789. },
  71790. enumerable: true,
  71791. configurable: true
  71792. });
  71793. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71794. /**
  71795. * Fired when the grip button on this controller is modified
  71796. */
  71797. get: function () {
  71798. return this.onMainButtonStateChangedObservable;
  71799. },
  71800. enumerable: true,
  71801. configurable: true
  71802. });
  71803. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71804. /**
  71805. * Fired when the thumbstick button on this controller is modified
  71806. */
  71807. get: function () {
  71808. return this.onPadStateChangedObservable;
  71809. },
  71810. enumerable: true,
  71811. configurable: true
  71812. });
  71813. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71814. /**
  71815. * Fired when the touchpad button on this controller is modified
  71816. */
  71817. get: function () {
  71818. return this.onTrackpadChangedObservable;
  71819. },
  71820. enumerable: true,
  71821. configurable: true
  71822. });
  71823. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71824. /**
  71825. * Fired when the touchpad values on this controller are modified
  71826. */
  71827. get: function () {
  71828. return this.onTrackpadValuesChangedObservable;
  71829. },
  71830. enumerable: true,
  71831. configurable: true
  71832. });
  71833. /**
  71834. * Called once per frame by the engine.
  71835. */
  71836. WindowsMotionController.prototype.update = function () {
  71837. _super.prototype.update.call(this);
  71838. if (this.browserGamepad.axes) {
  71839. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71840. this.trackpad.x = this.browserGamepad["axes"][2];
  71841. this.trackpad.y = this.browserGamepad["axes"][3];
  71842. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71843. }
  71844. // Only need to animate axes if there is a loaded mesh
  71845. if (this._loadedMeshInfo) {
  71846. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71847. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71848. }
  71849. }
  71850. }
  71851. };
  71852. /**
  71853. * Called once for each button that changed state since the last frame
  71854. * @param buttonIdx Which button index changed
  71855. * @param state New state of the button
  71856. * @param changes Which properties on the state changed since last frame
  71857. */
  71858. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71859. var buttonName = this._mapping.buttons[buttonIdx];
  71860. if (!buttonName) {
  71861. return;
  71862. }
  71863. // Only emit events for buttons that we know how to map from index to name
  71864. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71865. if (observable) {
  71866. observable.notifyObservers(state);
  71867. }
  71868. this._lerpButtonTransform(buttonName, state.value);
  71869. };
  71870. /**
  71871. * Moves the buttons on the controller mesh based on their current state
  71872. * @param buttonName the name of the button to move
  71873. * @param buttonValue the value of the button which determines the buttons new position
  71874. */
  71875. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71876. // If there is no loaded mesh, there is nothing to transform.
  71877. if (!this._loadedMeshInfo) {
  71878. return;
  71879. }
  71880. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71881. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71882. return;
  71883. }
  71884. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71885. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71886. };
  71887. /**
  71888. * Moves the axis on the controller mesh based on its current state
  71889. * @param axis the index of the axis
  71890. * @param axisValue the value of the axis which determines the meshes new position
  71891. * @hidden
  71892. */
  71893. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71894. if (!this._loadedMeshInfo) {
  71895. return;
  71896. }
  71897. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71898. if (!meshInfo) {
  71899. return;
  71900. }
  71901. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71902. return;
  71903. }
  71904. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71905. var lerpValue = axisValue * 0.5 + 0.5;
  71906. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71907. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71908. };
  71909. /**
  71910. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71911. * @param scene scene in which to add meshes
  71912. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71913. */
  71914. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71915. var _this = this;
  71916. if (forceDefault === void 0) { forceDefault = false; }
  71917. var path;
  71918. var filename;
  71919. // Checking if GLB loader is present
  71920. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71921. // Determine the device specific folder based on the ID suffix
  71922. var device = 'default';
  71923. if (this.id && !forceDefault) {
  71924. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71925. device = ((match && match[0]) || device);
  71926. }
  71927. // Hand
  71928. if (this.hand === 'left') {
  71929. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71930. }
  71931. else { // Right is the default if no hand is specified
  71932. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71933. }
  71934. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71935. }
  71936. else {
  71937. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71938. path = BABYLON.GenericController.MODEL_BASE_URL;
  71939. filename = BABYLON.GenericController.MODEL_FILENAME;
  71940. }
  71941. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71942. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71943. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71944. if (!_this._loadedMeshInfo) {
  71945. return;
  71946. }
  71947. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71948. _this.attachToMesh(_this._defaultModel);
  71949. if (meshLoaded) {
  71950. meshLoaded(_this._defaultModel);
  71951. }
  71952. }, null, function (scene, message) {
  71953. BABYLON.Tools.Log(message);
  71954. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71955. if (!forceDefault) {
  71956. _this.initControllerMesh(scene, meshLoaded, true);
  71957. }
  71958. });
  71959. };
  71960. /**
  71961. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71962. * can be transformed by button presses and axes values, based on this._mapping.
  71963. *
  71964. * @param scene scene in which the meshes exist
  71965. * @param meshes list of meshes that make up the controller model to process
  71966. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71967. */
  71968. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71969. var loadedMeshInfo = null;
  71970. // Create a new mesh to contain the glTF hierarchy
  71971. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71972. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71973. var childMesh = null;
  71974. for (var i = 0; i < meshes.length; i++) {
  71975. var mesh = meshes[i];
  71976. if (!mesh.parent) {
  71977. // Exclude controller meshes from picking results
  71978. mesh.isPickable = false;
  71979. // Handle root node, attach to the new parentMesh
  71980. childMesh = mesh;
  71981. break;
  71982. }
  71983. }
  71984. if (childMesh) {
  71985. childMesh.setParent(parentMesh);
  71986. // Create our mesh info. Note that this method will always return non-null.
  71987. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71988. }
  71989. else {
  71990. BABYLON.Tools.Warn('Could not find root node in model file.');
  71991. }
  71992. return loadedMeshInfo;
  71993. };
  71994. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71995. var loadedMeshInfo = new LoadedMeshInfo();
  71996. var i;
  71997. loadedMeshInfo.rootNode = rootNode;
  71998. // Reset the caches
  71999. loadedMeshInfo.buttonMeshes = {};
  72000. loadedMeshInfo.axisMeshes = {};
  72001. // Button Meshes
  72002. for (i = 0; i < this._mapping.buttons.length; i++) {
  72003. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72004. if (!buttonMeshName) {
  72005. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72006. continue;
  72007. }
  72008. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72009. if (!buttonMesh) {
  72010. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72011. continue;
  72012. }
  72013. var buttonMeshInfo = {
  72014. index: i,
  72015. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72016. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72017. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72018. };
  72019. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72020. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72021. }
  72022. else {
  72023. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72024. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72025. '(VALUE: ' + !!buttonMeshInfo.value +
  72026. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72027. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72028. ')');
  72029. }
  72030. }
  72031. // Axis Meshes
  72032. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72033. var axisMeshName = this._mapping.axisMeshNames[i];
  72034. if (!axisMeshName) {
  72035. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72036. continue;
  72037. }
  72038. var axisMesh = getChildByName(rootNode, axisMeshName);
  72039. if (!axisMesh) {
  72040. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72041. continue;
  72042. }
  72043. var axisMeshInfo = {
  72044. index: i,
  72045. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72046. min: getImmediateChildByName(axisMesh, 'MIN'),
  72047. max: getImmediateChildByName(axisMesh, 'MAX')
  72048. };
  72049. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72050. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72051. }
  72052. else {
  72053. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72054. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72055. '(VALUE: ' + !!axisMeshInfo.value +
  72056. ', MIN: ' + !!axisMeshInfo.min +
  72057. ', MAX:' + !!axisMeshInfo.max +
  72058. ')');
  72059. }
  72060. }
  72061. // Pointing Ray
  72062. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72063. if (!loadedMeshInfo.pointingPoseNode) {
  72064. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72065. }
  72066. return loadedMeshInfo;
  72067. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72068. function getChildByName(node, name) {
  72069. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72070. }
  72071. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72072. function getImmediateChildByName(node, name) {
  72073. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72074. }
  72075. };
  72076. /**
  72077. * Gets the ray of the controller in the direction the controller is pointing
  72078. * @param length the length the resulting ray should be
  72079. * @returns a ray in the direction the controller is pointing
  72080. */
  72081. WindowsMotionController.prototype.getForwardRay = function (length) {
  72082. if (length === void 0) { length = 100; }
  72083. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72084. return _super.prototype.getForwardRay.call(this, length);
  72085. }
  72086. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72087. var origin = m.getTranslation();
  72088. var forward = new BABYLON.Vector3(0, 0, -1);
  72089. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72090. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72091. return new BABYLON.Ray(origin, direction, length);
  72092. };
  72093. /**
  72094. * Disposes of the controller
  72095. */
  72096. WindowsMotionController.prototype.dispose = function () {
  72097. _super.prototype.dispose.call(this);
  72098. this.onTrackpadChangedObservable.clear();
  72099. };
  72100. /**
  72101. * The base url used to load the left and right controller models
  72102. */
  72103. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72104. /**
  72105. * The name of the left controller model file
  72106. */
  72107. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72108. /**
  72109. * The name of the right controller model file
  72110. */
  72111. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72112. /**
  72113. * The controller name prefix for this controller type
  72114. */
  72115. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72116. /**
  72117. * The controller id pattern for this controller type
  72118. */
  72119. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72120. return WindowsMotionController;
  72121. }(BABYLON.WebVRController));
  72122. BABYLON.WindowsMotionController = WindowsMotionController;
  72123. })(BABYLON || (BABYLON = {}));
  72124. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72125. var BABYLON;
  72126. (function (BABYLON) {
  72127. /**
  72128. * Gear VR Controller
  72129. */
  72130. var GearVRController = /** @class */ (function (_super) {
  72131. __extends(GearVRController, _super);
  72132. /**
  72133. * Creates a new GearVRController from a gamepad
  72134. * @param vrGamepad the gamepad that the controller should be created from
  72135. */
  72136. function GearVRController(vrGamepad) {
  72137. var _this = _super.call(this, vrGamepad) || this;
  72138. _this._buttonIndexToObservableNameMap = [
  72139. 'onTrackpadChangedObservable',
  72140. 'onTriggerStateChangedObservable' // Trigger
  72141. ];
  72142. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72143. return _this;
  72144. }
  72145. /**
  72146. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72147. * @param scene scene in which to add meshes
  72148. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72149. */
  72150. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72151. var _this = this;
  72152. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72153. _this._defaultModel = newMeshes[1];
  72154. _this.attachToMesh(_this._defaultModel);
  72155. if (meshLoaded) {
  72156. meshLoaded(_this._defaultModel);
  72157. }
  72158. });
  72159. };
  72160. /**
  72161. * Called once for each button that changed state since the last frame
  72162. * @param buttonIdx Which button index changed
  72163. * @param state New state of the button
  72164. * @param changes Which properties on the state changed since last frame
  72165. */
  72166. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72167. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72168. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72169. // Only emit events for buttons that we know how to map from index to observable
  72170. var observable = this[observableName];
  72171. if (observable) {
  72172. observable.notifyObservers(state);
  72173. }
  72174. }
  72175. };
  72176. /**
  72177. * Base Url for the controller model.
  72178. */
  72179. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72180. /**
  72181. * File name for the controller model.
  72182. */
  72183. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72184. /**
  72185. * Gamepad Id prefix used to identify this controller.
  72186. */
  72187. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72188. return GearVRController;
  72189. }(BABYLON.WebVRController));
  72190. BABYLON.GearVRController = GearVRController;
  72191. })(BABYLON || (BABYLON = {}));
  72192. //# sourceMappingURL=babylon.gearVRController.js.map
  72193. var BABYLON;
  72194. (function (BABYLON) {
  72195. /**
  72196. * Google Daydream controller
  72197. */
  72198. var DaydreamController = /** @class */ (function (_super) {
  72199. __extends(DaydreamController, _super);
  72200. /**
  72201. * Creates a new DaydreamController from a gamepad
  72202. * @param vrGamepad the gamepad that the controller should be created from
  72203. */
  72204. function DaydreamController(vrGamepad) {
  72205. var _this = _super.call(this, vrGamepad) || this;
  72206. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72207. return _this;
  72208. }
  72209. /**
  72210. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72211. * @param scene scene in which to add meshes
  72212. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72213. */
  72214. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72215. var _this = this;
  72216. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72217. _this._defaultModel = newMeshes[1];
  72218. _this.attachToMesh(_this._defaultModel);
  72219. if (meshLoaded) {
  72220. meshLoaded(_this._defaultModel);
  72221. }
  72222. });
  72223. };
  72224. /**
  72225. * Called once for each button that changed state since the last frame
  72226. * @param buttonIdx Which button index changed
  72227. * @param state New state of the button
  72228. * @param changes Which properties on the state changed since last frame
  72229. */
  72230. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72231. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72232. if (buttonIdx === 0) {
  72233. var observable = this.onTriggerStateChangedObservable;
  72234. if (observable) {
  72235. observable.notifyObservers(state);
  72236. }
  72237. }
  72238. else {
  72239. // If the app or home buttons are ever made available
  72240. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72241. }
  72242. };
  72243. /**
  72244. * Base Url for the controller model.
  72245. */
  72246. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72247. /**
  72248. * File name for the controller model.
  72249. */
  72250. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72251. /**
  72252. * Gamepad Id prefix used to identify Daydream Controller.
  72253. */
  72254. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72255. return DaydreamController;
  72256. }(BABYLON.WebVRController));
  72257. BABYLON.DaydreamController = DaydreamController;
  72258. })(BABYLON || (BABYLON = {}));
  72259. //# sourceMappingURL=babylon.daydreamController.js.map
  72260. var BABYLON;
  72261. (function (BABYLON) {
  72262. var FollowCamera = /** @class */ (function (_super) {
  72263. __extends(FollowCamera, _super);
  72264. function FollowCamera(name, position, scene, lockedTarget) {
  72265. if (lockedTarget === void 0) { lockedTarget = null; }
  72266. var _this = _super.call(this, name, position, scene) || this;
  72267. _this.radius = 12;
  72268. _this.rotationOffset = 0;
  72269. _this.heightOffset = 4;
  72270. _this.cameraAcceleration = 0.05;
  72271. _this.maxCameraSpeed = 20;
  72272. _this.lockedTarget = lockedTarget;
  72273. return _this;
  72274. }
  72275. FollowCamera.prototype.getRadians = function (degrees) {
  72276. return degrees * Math.PI / 180;
  72277. };
  72278. FollowCamera.prototype.follow = function (cameraTarget) {
  72279. if (!cameraTarget)
  72280. return;
  72281. var yRotation;
  72282. if (cameraTarget.rotationQuaternion) {
  72283. var rotMatrix = new BABYLON.Matrix();
  72284. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72285. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72286. }
  72287. else {
  72288. yRotation = cameraTarget.rotation.y;
  72289. }
  72290. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72291. var targetPosition = cameraTarget.getAbsolutePosition();
  72292. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72293. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72294. var dx = targetX - this.position.x;
  72295. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72296. var dz = (targetZ) - this.position.z;
  72297. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72298. var vy = dy * this.cameraAcceleration;
  72299. var vz = dz * this.cameraAcceleration * 2;
  72300. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72301. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72302. }
  72303. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72304. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72305. }
  72306. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72307. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72308. }
  72309. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72310. this.setTarget(targetPosition);
  72311. };
  72312. FollowCamera.prototype._checkInputs = function () {
  72313. _super.prototype._checkInputs.call(this);
  72314. if (this.lockedTarget) {
  72315. this.follow(this.lockedTarget);
  72316. }
  72317. };
  72318. FollowCamera.prototype.getClassName = function () {
  72319. return "FollowCamera";
  72320. };
  72321. __decorate([
  72322. BABYLON.serialize()
  72323. ], FollowCamera.prototype, "radius", void 0);
  72324. __decorate([
  72325. BABYLON.serialize()
  72326. ], FollowCamera.prototype, "rotationOffset", void 0);
  72327. __decorate([
  72328. BABYLON.serialize()
  72329. ], FollowCamera.prototype, "heightOffset", void 0);
  72330. __decorate([
  72331. BABYLON.serialize()
  72332. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72333. __decorate([
  72334. BABYLON.serialize()
  72335. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72336. __decorate([
  72337. BABYLON.serializeAsMeshReference("lockedTargetId")
  72338. ], FollowCamera.prototype, "lockedTarget", void 0);
  72339. return FollowCamera;
  72340. }(BABYLON.TargetCamera));
  72341. BABYLON.FollowCamera = FollowCamera;
  72342. var ArcFollowCamera = /** @class */ (function (_super) {
  72343. __extends(ArcFollowCamera, _super);
  72344. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72345. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72346. _this.alpha = alpha;
  72347. _this.beta = beta;
  72348. _this.radius = radius;
  72349. _this.target = target;
  72350. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72351. _this.follow();
  72352. return _this;
  72353. }
  72354. ArcFollowCamera.prototype.follow = function () {
  72355. if (!this.target) {
  72356. return;
  72357. }
  72358. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72359. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72360. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72361. var targetPosition = this.target.getAbsolutePosition();
  72362. this.position = targetPosition.add(this._cartesianCoordinates);
  72363. this.setTarget(targetPosition);
  72364. };
  72365. ArcFollowCamera.prototype._checkInputs = function () {
  72366. _super.prototype._checkInputs.call(this);
  72367. this.follow();
  72368. };
  72369. ArcFollowCamera.prototype.getClassName = function () {
  72370. return "ArcFollowCamera";
  72371. };
  72372. return ArcFollowCamera;
  72373. }(BABYLON.TargetCamera));
  72374. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72375. })(BABYLON || (BABYLON = {}));
  72376. //# sourceMappingURL=babylon.followCamera.js.map
  72377. var BABYLON;
  72378. (function (BABYLON) {
  72379. // We're mainly based on the logic defined into the FreeCamera code
  72380. var UniversalCamera = /** @class */ (function (_super) {
  72381. __extends(UniversalCamera, _super);
  72382. //-- end properties for backward compatibility for inputs
  72383. function UniversalCamera(name, position, scene) {
  72384. var _this = _super.call(this, name, position, scene) || this;
  72385. _this.inputs.addGamepad();
  72386. return _this;
  72387. }
  72388. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72389. //-- Begin properties for backward compatibility for inputs
  72390. get: function () {
  72391. var gamepad = this.inputs.attached["gamepad"];
  72392. if (gamepad)
  72393. return gamepad.gamepadAngularSensibility;
  72394. return 0;
  72395. },
  72396. set: function (value) {
  72397. var gamepad = this.inputs.attached["gamepad"];
  72398. if (gamepad)
  72399. gamepad.gamepadAngularSensibility = value;
  72400. },
  72401. enumerable: true,
  72402. configurable: true
  72403. });
  72404. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72405. get: function () {
  72406. var gamepad = this.inputs.attached["gamepad"];
  72407. if (gamepad)
  72408. return gamepad.gamepadMoveSensibility;
  72409. return 0;
  72410. },
  72411. set: function (value) {
  72412. var gamepad = this.inputs.attached["gamepad"];
  72413. if (gamepad)
  72414. gamepad.gamepadMoveSensibility = value;
  72415. },
  72416. enumerable: true,
  72417. configurable: true
  72418. });
  72419. UniversalCamera.prototype.getClassName = function () {
  72420. return "UniversalCamera";
  72421. };
  72422. return UniversalCamera;
  72423. }(BABYLON.TouchCamera));
  72424. BABYLON.UniversalCamera = UniversalCamera;
  72425. })(BABYLON || (BABYLON = {}));
  72426. //# sourceMappingURL=babylon.universalCamera.js.map
  72427. var BABYLON;
  72428. (function (BABYLON) {
  72429. // We're mainly based on the logic defined into the FreeCamera code
  72430. var GamepadCamera = /** @class */ (function (_super) {
  72431. __extends(GamepadCamera, _super);
  72432. //-- end properties for backward compatibility for inputs
  72433. function GamepadCamera(name, position, scene) {
  72434. return _super.call(this, name, position, scene) || this;
  72435. }
  72436. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72437. //-- Begin properties for backward compatibility for inputs
  72438. get: function () {
  72439. var gamepad = this.inputs.attached["gamepad"];
  72440. if (gamepad)
  72441. return gamepad.gamepadAngularSensibility;
  72442. return 0;
  72443. },
  72444. set: function (value) {
  72445. var gamepad = this.inputs.attached["gamepad"];
  72446. if (gamepad)
  72447. gamepad.gamepadAngularSensibility = value;
  72448. },
  72449. enumerable: true,
  72450. configurable: true
  72451. });
  72452. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72453. get: function () {
  72454. var gamepad = this.inputs.attached["gamepad"];
  72455. if (gamepad)
  72456. return gamepad.gamepadMoveSensibility;
  72457. return 0;
  72458. },
  72459. set: function (value) {
  72460. var gamepad = this.inputs.attached["gamepad"];
  72461. if (gamepad)
  72462. gamepad.gamepadMoveSensibility = value;
  72463. },
  72464. enumerable: true,
  72465. configurable: true
  72466. });
  72467. GamepadCamera.prototype.getClassName = function () {
  72468. return "GamepadCamera";
  72469. };
  72470. return GamepadCamera;
  72471. }(BABYLON.UniversalCamera));
  72472. BABYLON.GamepadCamera = GamepadCamera;
  72473. })(BABYLON || (BABYLON = {}));
  72474. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72475. var BABYLON;
  72476. (function (BABYLON) {
  72477. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72478. function PostProcessRenderPipelineManager() {
  72479. this._renderPipelines = {};
  72480. }
  72481. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72482. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72483. };
  72484. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72485. if (unique === void 0) { unique = false; }
  72486. var renderPipeline = this._renderPipelines[renderPipelineName];
  72487. if (!renderPipeline) {
  72488. return;
  72489. }
  72490. renderPipeline._attachCameras(cameras, unique);
  72491. };
  72492. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72493. var renderPipeline = this._renderPipelines[renderPipelineName];
  72494. if (!renderPipeline) {
  72495. return;
  72496. }
  72497. renderPipeline._detachCameras(cameras);
  72498. };
  72499. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72500. var renderPipeline = this._renderPipelines[renderPipelineName];
  72501. if (!renderPipeline) {
  72502. return;
  72503. }
  72504. renderPipeline._enableEffect(renderEffectName, cameras);
  72505. };
  72506. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72507. var renderPipeline = this._renderPipelines[renderPipelineName];
  72508. if (!renderPipeline) {
  72509. return;
  72510. }
  72511. renderPipeline._disableEffect(renderEffectName, cameras);
  72512. };
  72513. PostProcessRenderPipelineManager.prototype.update = function () {
  72514. for (var renderPipelineName in this._renderPipelines) {
  72515. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72516. var pipeline = this._renderPipelines[renderPipelineName];
  72517. if (!pipeline.isSupported) {
  72518. pipeline.dispose();
  72519. delete this._renderPipelines[renderPipelineName];
  72520. }
  72521. else {
  72522. pipeline._update();
  72523. }
  72524. }
  72525. }
  72526. };
  72527. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72528. for (var renderPipelineName in this._renderPipelines) {
  72529. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72530. var pipeline = this._renderPipelines[renderPipelineName];
  72531. pipeline._rebuild();
  72532. }
  72533. }
  72534. };
  72535. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72536. for (var renderPipelineName in this._renderPipelines) {
  72537. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72538. var pipeline = this._renderPipelines[renderPipelineName];
  72539. pipeline.dispose();
  72540. }
  72541. }
  72542. };
  72543. return PostProcessRenderPipelineManager;
  72544. }());
  72545. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72546. })(BABYLON || (BABYLON = {}));
  72547. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72548. var BABYLON;
  72549. (function (BABYLON) {
  72550. /**
  72551. * This represents a set of one or more post processes in Babylon.
  72552. * A post process can be used to apply a shader to a texture after it is rendered.
  72553. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72554. */
  72555. var PostProcessRenderEffect = /** @class */ (function () {
  72556. /**
  72557. * Instantiates a post process render effect.
  72558. * A post process can be used to apply a shader to a texture after it is rendered.
  72559. * @param engine The engine the effect is tied to
  72560. * @param name The name of the effect
  72561. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72562. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72563. */
  72564. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72565. this._name = name;
  72566. this._singleInstance = singleInstance || true;
  72567. this._getPostProcesses = getPostProcesses;
  72568. this._cameras = {};
  72569. this._indicesForCamera = {};
  72570. this._postProcesses = {};
  72571. }
  72572. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72573. /**
  72574. * Checks if all the post processes in the effect are supported.
  72575. */
  72576. get: function () {
  72577. for (var index in this._postProcesses) {
  72578. if (this._postProcesses.hasOwnProperty(index)) {
  72579. var pps = this._postProcesses[index];
  72580. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72581. if (!pps[ppIndex].isSupported) {
  72582. return false;
  72583. }
  72584. }
  72585. }
  72586. }
  72587. return true;
  72588. },
  72589. enumerable: true,
  72590. configurable: true
  72591. });
  72592. /**
  72593. * Updates the current state of the effect
  72594. */
  72595. PostProcessRenderEffect.prototype._update = function () {
  72596. };
  72597. /**
  72598. * Attaches the effect on cameras
  72599. * @param cameras The camera to attach to.
  72600. */
  72601. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72602. var _this = this;
  72603. var cameraKey;
  72604. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72605. if (!cams) {
  72606. return;
  72607. }
  72608. for (var i = 0; i < cams.length; i++) {
  72609. var camera = cams[i];
  72610. var cameraName = camera.name;
  72611. if (this._singleInstance) {
  72612. cameraKey = 0;
  72613. }
  72614. else {
  72615. cameraKey = cameraName;
  72616. }
  72617. if (!this._postProcesses[cameraKey]) {
  72618. var postProcess = this._getPostProcesses();
  72619. if (postProcess) {
  72620. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72621. }
  72622. }
  72623. if (!this._indicesForCamera[cameraName]) {
  72624. this._indicesForCamera[cameraName] = [];
  72625. }
  72626. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72627. var index = camera.attachPostProcess(postProcess);
  72628. _this._indicesForCamera[cameraName].push(index);
  72629. });
  72630. if (!this._cameras[cameraName]) {
  72631. this._cameras[cameraName] = camera;
  72632. }
  72633. }
  72634. };
  72635. /**
  72636. * Detatches the effect on cameras
  72637. * @param cameras The camera to detatch from.
  72638. */
  72639. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72640. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72641. if (!cams) {
  72642. return;
  72643. }
  72644. for (var i = 0; i < cams.length; i++) {
  72645. var camera = cams[i];
  72646. var cameraName = camera.name;
  72647. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72648. camera.detachPostProcess(postProcess);
  72649. });
  72650. if (this._cameras[cameraName]) {
  72651. //this._indicesForCamera.splice(index, 1);
  72652. this._cameras[cameraName] = null;
  72653. }
  72654. }
  72655. };
  72656. /**
  72657. * Enables the effect on given cameras
  72658. * @param cameras The camera to enable.
  72659. */
  72660. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72661. var _this = this;
  72662. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72663. if (!cams) {
  72664. return;
  72665. }
  72666. for (var i = 0; i < cams.length; i++) {
  72667. var camera = cams[i];
  72668. var cameraName = camera.name;
  72669. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72670. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72671. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72672. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72673. });
  72674. }
  72675. }
  72676. }
  72677. };
  72678. /**
  72679. * Disables the effect on the given cameras
  72680. * @param cameras The camera to disable.
  72681. */
  72682. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72683. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72684. if (!cams) {
  72685. return;
  72686. }
  72687. for (var i = 0; i < cams.length; i++) {
  72688. var camera = cams[i];
  72689. var cameraName = camera.name;
  72690. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72691. camera.detachPostProcess(postProcess);
  72692. });
  72693. }
  72694. };
  72695. /**
  72696. * Gets a list of the post processes contained in the effect.
  72697. * @param camera The camera to get the post processes on.
  72698. * @returns The list of the post processes in the effect.
  72699. */
  72700. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72701. if (this._singleInstance) {
  72702. return this._postProcesses[0];
  72703. }
  72704. else {
  72705. if (!camera) {
  72706. return null;
  72707. }
  72708. return this._postProcesses[camera.name];
  72709. }
  72710. };
  72711. return PostProcessRenderEffect;
  72712. }());
  72713. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72714. })(BABYLON || (BABYLON = {}));
  72715. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72716. var BABYLON;
  72717. (function (BABYLON) {
  72718. var PostProcessRenderPipeline = /** @class */ (function () {
  72719. function PostProcessRenderPipeline(engine, name) {
  72720. this.engine = engine;
  72721. this._name = name;
  72722. this._renderEffects = {};
  72723. this._renderEffectsForIsolatedPass = new Array();
  72724. this._cameras = [];
  72725. }
  72726. PostProcessRenderPipeline.prototype.getClassName = function () {
  72727. return "PostProcessRenderPipeline";
  72728. };
  72729. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72730. get: function () {
  72731. for (var renderEffectName in this._renderEffects) {
  72732. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72733. if (!this._renderEffects[renderEffectName].isSupported) {
  72734. return false;
  72735. }
  72736. }
  72737. }
  72738. return true;
  72739. },
  72740. enumerable: true,
  72741. configurable: true
  72742. });
  72743. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72744. this._renderEffects[renderEffect._name] = renderEffect;
  72745. };
  72746. // private
  72747. PostProcessRenderPipeline.prototype._rebuild = function () {
  72748. };
  72749. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72750. var renderEffects = this._renderEffects[renderEffectName];
  72751. if (!renderEffects) {
  72752. return;
  72753. }
  72754. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72755. };
  72756. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72757. var renderEffects = this._renderEffects[renderEffectName];
  72758. if (!renderEffects) {
  72759. return;
  72760. }
  72761. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72762. };
  72763. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72764. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72765. if (!cams) {
  72766. return;
  72767. }
  72768. var indicesToDelete = [];
  72769. var i;
  72770. for (i = 0; i < cams.length; i++) {
  72771. var camera = cams[i];
  72772. var cameraName = camera.name;
  72773. if (this._cameras.indexOf(camera) === -1) {
  72774. this._cameras[cameraName] = camera;
  72775. }
  72776. else if (unique) {
  72777. indicesToDelete.push(i);
  72778. }
  72779. }
  72780. for (i = 0; i < indicesToDelete.length; i++) {
  72781. cameras.splice(indicesToDelete[i], 1);
  72782. }
  72783. for (var renderEffectName in this._renderEffects) {
  72784. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72785. this._renderEffects[renderEffectName]._attachCameras(cams);
  72786. }
  72787. }
  72788. };
  72789. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72790. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72791. if (!cams) {
  72792. return;
  72793. }
  72794. for (var renderEffectName in this._renderEffects) {
  72795. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72796. this._renderEffects[renderEffectName]._detachCameras(cams);
  72797. }
  72798. }
  72799. for (var i = 0; i < cams.length; i++) {
  72800. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72801. }
  72802. };
  72803. PostProcessRenderPipeline.prototype._update = function () {
  72804. for (var renderEffectName in this._renderEffects) {
  72805. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72806. this._renderEffects[renderEffectName]._update();
  72807. }
  72808. }
  72809. for (var i = 0; i < this._cameras.length; i++) {
  72810. var cameraName = this._cameras[i].name;
  72811. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72812. this._renderEffectsForIsolatedPass[cameraName]._update();
  72813. }
  72814. }
  72815. };
  72816. PostProcessRenderPipeline.prototype._reset = function () {
  72817. this._renderEffects = {};
  72818. this._renderEffectsForIsolatedPass = new Array();
  72819. };
  72820. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72821. // 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)
  72822. var effectKeys = Object.keys(this._renderEffects);
  72823. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72824. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72825. if (postProcesses) {
  72826. postProcesses[0].samples = sampleCount;
  72827. return true;
  72828. }
  72829. }
  72830. return false;
  72831. };
  72832. PostProcessRenderPipeline.prototype.dispose = function () {
  72833. // Must be implemented by children
  72834. };
  72835. __decorate([
  72836. BABYLON.serialize()
  72837. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72838. return PostProcessRenderPipeline;
  72839. }());
  72840. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72841. })(BABYLON || (BABYLON = {}));
  72842. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72843. var BABYLON;
  72844. (function (BABYLON) {
  72845. /**
  72846. * This represents a depth renderer in Babylon.
  72847. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72848. */
  72849. var DepthRenderer = /** @class */ (function () {
  72850. /**
  72851. * Instantiates a depth renderer
  72852. * @param scene The scene the renderer belongs to
  72853. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72854. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72855. */
  72856. function DepthRenderer(scene, type, camera) {
  72857. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72858. if (camera === void 0) { camera = null; }
  72859. var _this = this;
  72860. this._scene = scene;
  72861. this._camera = camera;
  72862. var engine = scene.getEngine();
  72863. // Render target
  72864. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72865. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72866. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72867. this._depthMap.refreshRate = 1;
  72868. this._depthMap.renderParticles = false;
  72869. this._depthMap.renderList = null;
  72870. // Camera to get depth map from to support multiple concurrent cameras
  72871. this._depthMap.activeCamera = this._camera;
  72872. this._depthMap.ignoreCameraViewport = true;
  72873. this._depthMap.useCameraPostProcesses = false;
  72874. // set default depth value to 1.0 (far away)
  72875. this._depthMap.onClearObservable.add(function (engine) {
  72876. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72877. });
  72878. // Custom render function
  72879. var renderSubMesh = function (subMesh) {
  72880. var mesh = subMesh.getRenderingMesh();
  72881. var scene = _this._scene;
  72882. var engine = scene.getEngine();
  72883. var material = subMesh.getMaterial();
  72884. if (!material) {
  72885. return;
  72886. }
  72887. // Culling and reverse (right handed system)
  72888. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72889. // Managing instances
  72890. var batch = mesh._getInstancesRenderList(subMesh._id);
  72891. if (batch.mustReturn) {
  72892. return;
  72893. }
  72894. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72895. var camera = _this._camera || scene.activeCamera;
  72896. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72897. engine.enableEffect(_this._effect);
  72898. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72899. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72900. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72901. // Alpha test
  72902. if (material && material.needAlphaTesting()) {
  72903. var alphaTexture = material.getAlphaTestTexture();
  72904. if (alphaTexture) {
  72905. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72906. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72907. }
  72908. }
  72909. // Bones
  72910. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72911. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72912. }
  72913. // Draw
  72914. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72915. }
  72916. };
  72917. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72918. var index;
  72919. if (depthOnlySubMeshes.length) {
  72920. engine.setColorWrite(false);
  72921. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72922. renderSubMesh(depthOnlySubMeshes.data[index]);
  72923. }
  72924. engine.setColorWrite(true);
  72925. }
  72926. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72927. renderSubMesh(opaqueSubMeshes.data[index]);
  72928. }
  72929. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72930. renderSubMesh(alphaTestSubMeshes.data[index]);
  72931. }
  72932. };
  72933. }
  72934. /**
  72935. * Creates the depth rendering effect and checks if the effect is ready.
  72936. * @param subMesh The submesh to be used to render the depth map of
  72937. * @param useInstances If multiple world instances should be used
  72938. * @returns if the depth renderer is ready to render the depth map
  72939. */
  72940. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72941. var material = subMesh.getMaterial();
  72942. if (material.disableDepthWrite) {
  72943. return false;
  72944. }
  72945. var defines = [];
  72946. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72947. var mesh = subMesh.getMesh();
  72948. // Alpha test
  72949. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72950. defines.push("#define ALPHATEST");
  72951. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72952. attribs.push(BABYLON.VertexBuffer.UVKind);
  72953. defines.push("#define UV1");
  72954. }
  72955. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72956. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72957. defines.push("#define UV2");
  72958. }
  72959. }
  72960. // Bones
  72961. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72962. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72963. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72964. if (mesh.numBoneInfluencers > 4) {
  72965. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72966. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72967. }
  72968. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72969. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72970. }
  72971. else {
  72972. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72973. }
  72974. // Instances
  72975. if (useInstances) {
  72976. defines.push("#define INSTANCES");
  72977. attribs.push("world0");
  72978. attribs.push("world1");
  72979. attribs.push("world2");
  72980. attribs.push("world3");
  72981. }
  72982. // Get correct effect
  72983. var join = defines.join("\n");
  72984. if (this._cachedDefines !== join) {
  72985. this._cachedDefines = join;
  72986. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72987. }
  72988. return this._effect.isReady();
  72989. };
  72990. /**
  72991. * Gets the texture which the depth map will be written to.
  72992. * @returns The depth map texture
  72993. */
  72994. DepthRenderer.prototype.getDepthMap = function () {
  72995. return this._depthMap;
  72996. };
  72997. /**
  72998. * Disposes of the depth renderer.
  72999. */
  73000. DepthRenderer.prototype.dispose = function () {
  73001. this._depthMap.dispose();
  73002. };
  73003. return DepthRenderer;
  73004. }());
  73005. BABYLON.DepthRenderer = DepthRenderer;
  73006. })(BABYLON || (BABYLON = {}));
  73007. //# sourceMappingURL=babylon.depthRenderer.js.map
  73008. var BABYLON;
  73009. (function (BABYLON) {
  73010. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73011. __extends(SSAORenderingPipeline, _super);
  73012. /**
  73013. * @constructor
  73014. * @param {string} name - The rendering pipeline name
  73015. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73016. * @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 }
  73017. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73018. */
  73019. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73020. var _this = _super.call(this, scene.getEngine(), name) || this;
  73021. // Members
  73022. /**
  73023. * The PassPostProcess id in the pipeline that contains the original scene color
  73024. */
  73025. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73026. /**
  73027. * The SSAO PostProcess id in the pipeline
  73028. */
  73029. _this.SSAORenderEffect = "SSAORenderEffect";
  73030. /**
  73031. * The horizontal blur PostProcess id in the pipeline
  73032. */
  73033. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73034. /**
  73035. * The vertical blur PostProcess id in the pipeline
  73036. */
  73037. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73038. /**
  73039. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73040. */
  73041. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73042. /**
  73043. * The output strength of the SSAO post-process. Default value is 1.0.
  73044. */
  73045. _this.totalStrength = 1.0;
  73046. /**
  73047. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73048. */
  73049. _this.radius = 0.0001;
  73050. /**
  73051. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73052. * Must not be equal to fallOff and superior to fallOff.
  73053. * Default value is 0.975
  73054. */
  73055. _this.area = 0.0075;
  73056. /**
  73057. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73058. * Must not be equal to area and inferior to area.
  73059. * Default value is 0.0
  73060. */
  73061. _this.fallOff = 0.000001;
  73062. /**
  73063. * The base color of the SSAO post-process
  73064. * The final result is "base + ssao" between [0, 1]
  73065. */
  73066. _this.base = 0.5;
  73067. _this._firstUpdate = true;
  73068. _this._scene = scene;
  73069. // Set up assets
  73070. _this._createRandomTexture();
  73071. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73072. var ssaoRatio = ratio.ssaoRatio || ratio;
  73073. var combineRatio = ratio.combineRatio || ratio;
  73074. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73075. _this._createSSAOPostProcess(ssaoRatio);
  73076. _this._createBlurPostProcess(ssaoRatio);
  73077. _this._createSSAOCombinePostProcess(combineRatio);
  73078. // Set up pipeline
  73079. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73080. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73081. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73082. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73083. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73084. // Finish
  73085. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73086. if (cameras)
  73087. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73088. return _this;
  73089. }
  73090. // Public Methods
  73091. /**
  73092. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73093. */
  73094. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73095. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73096. for (var i = 0; i < this._scene.cameras.length; i++) {
  73097. var camera = this._scene.cameras[i];
  73098. this._originalColorPostProcess.dispose(camera);
  73099. this._ssaoPostProcess.dispose(camera);
  73100. this._blurHPostProcess.dispose(camera);
  73101. this._blurVPostProcess.dispose(camera);
  73102. this._ssaoCombinePostProcess.dispose(camera);
  73103. }
  73104. this._randomTexture.dispose();
  73105. if (disableDepthRender)
  73106. this._scene.disableDepthRenderer();
  73107. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73108. _super.prototype.dispose.call(this);
  73109. };
  73110. // Private Methods
  73111. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73112. var _this = this;
  73113. var size = 16;
  73114. 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);
  73115. 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);
  73116. this._blurHPostProcess.onActivateObservable.add(function () {
  73117. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73118. _this._blurHPostProcess.kernel = size * dw;
  73119. });
  73120. this._blurVPostProcess.onActivateObservable.add(function () {
  73121. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73122. _this._blurVPostProcess.kernel = size * dw;
  73123. });
  73124. };
  73125. SSAORenderingPipeline.prototype._rebuild = function () {
  73126. this._firstUpdate = true;
  73127. _super.prototype._rebuild.call(this);
  73128. };
  73129. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73130. var _this = this;
  73131. var numSamples = 16;
  73132. var sampleSphere = [
  73133. 0.5381, 0.1856, -0.4319,
  73134. 0.1379, 0.2486, 0.4430,
  73135. 0.3371, 0.5679, -0.0057,
  73136. -0.6999, -0.0451, -0.0019,
  73137. 0.0689, -0.1598, -0.8547,
  73138. 0.0560, 0.0069, -0.1843,
  73139. -0.0146, 0.1402, 0.0762,
  73140. 0.0100, -0.1924, -0.0344,
  73141. -0.3577, -0.5301, -0.4358,
  73142. -0.3169, 0.1063, 0.0158,
  73143. 0.0103, -0.5869, 0.0046,
  73144. -0.0897, -0.4940, 0.3287,
  73145. 0.7119, -0.0154, -0.0918,
  73146. -0.0533, 0.0596, -0.5411,
  73147. 0.0352, -0.0631, 0.5460,
  73148. -0.4776, 0.2847, -0.0271
  73149. ];
  73150. var samplesFactor = 1.0 / numSamples;
  73151. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73152. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73153. "area", "fallOff", "base", "range", "viewport"
  73154. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73155. this._ssaoPostProcess.onApply = function (effect) {
  73156. if (_this._firstUpdate) {
  73157. effect.setArray3("sampleSphere", sampleSphere);
  73158. effect.setFloat("samplesFactor", samplesFactor);
  73159. effect.setFloat("randTextureTiles", 4.0);
  73160. }
  73161. effect.setFloat("totalStrength", _this.totalStrength);
  73162. effect.setFloat("radius", _this.radius);
  73163. effect.setFloat("area", _this.area);
  73164. effect.setFloat("fallOff", _this.fallOff);
  73165. effect.setFloat("base", _this.base);
  73166. effect.setTexture("textureSampler", _this._depthTexture);
  73167. effect.setTexture("randomSampler", _this._randomTexture);
  73168. };
  73169. };
  73170. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73171. var _this = this;
  73172. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73173. this._ssaoCombinePostProcess.onApply = function (effect) {
  73174. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73175. };
  73176. };
  73177. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73178. var size = 512;
  73179. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73180. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73181. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73182. var context = this._randomTexture.getContext();
  73183. var rand = function (min, max) {
  73184. return Math.random() * (max - min) + min;
  73185. };
  73186. var randVector = BABYLON.Vector3.Zero();
  73187. for (var x = 0; x < size; x++) {
  73188. for (var y = 0; y < size; y++) {
  73189. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73190. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73191. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73192. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73193. context.fillRect(x, y, 1, 1);
  73194. }
  73195. }
  73196. this._randomTexture.update(false);
  73197. };
  73198. __decorate([
  73199. BABYLON.serialize()
  73200. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73201. __decorate([
  73202. BABYLON.serialize()
  73203. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73204. __decorate([
  73205. BABYLON.serialize()
  73206. ], SSAORenderingPipeline.prototype, "area", void 0);
  73207. __decorate([
  73208. BABYLON.serialize()
  73209. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73210. __decorate([
  73211. BABYLON.serialize()
  73212. ], SSAORenderingPipeline.prototype, "base", void 0);
  73213. return SSAORenderingPipeline;
  73214. }(BABYLON.PostProcessRenderPipeline));
  73215. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73216. })(BABYLON || (BABYLON = {}));
  73217. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73218. var BABYLON;
  73219. (function (BABYLON) {
  73220. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73221. __extends(SSAO2RenderingPipeline, _super);
  73222. /**
  73223. * @constructor
  73224. * @param {string} name - The rendering pipeline name
  73225. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73226. * @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 }
  73227. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73228. */
  73229. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73230. var _this = _super.call(this, scene.getEngine(), name) || this;
  73231. // Members
  73232. /**
  73233. * The PassPostProcess id in the pipeline that contains the original scene color
  73234. */
  73235. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73236. /**
  73237. * The SSAO PostProcess id in the pipeline
  73238. */
  73239. _this.SSAORenderEffect = "SSAORenderEffect";
  73240. /**
  73241. * The horizontal blur PostProcess id in the pipeline
  73242. */
  73243. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73244. /**
  73245. * The vertical blur PostProcess id in the pipeline
  73246. */
  73247. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73248. /**
  73249. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73250. */
  73251. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73252. /**
  73253. * The output strength of the SSAO post-process. Default value is 1.0.
  73254. */
  73255. _this.totalStrength = 1.0;
  73256. /**
  73257. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73258. */
  73259. _this.maxZ = 100.0;
  73260. /**
  73261. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73262. */
  73263. _this.minZAspect = 0.2;
  73264. /**
  73265. * Number of samples used for the SSAO calculations. Default value is 8
  73266. */
  73267. _this._samples = 8;
  73268. /**
  73269. * Are we using bilateral blur ?
  73270. */
  73271. _this._expensiveBlur = true;
  73272. /**
  73273. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73274. */
  73275. _this.radius = 2.0;
  73276. /**
  73277. * The base color of the SSAO post-process
  73278. * The final result is "base + ssao" between [0, 1]
  73279. */
  73280. _this.base = 0.1;
  73281. _this._firstUpdate = true;
  73282. _this._scene = scene;
  73283. _this._ratio = ratio;
  73284. if (!_this.isSupported) {
  73285. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73286. return _this;
  73287. }
  73288. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73289. var blurRatio = _this._ratio.blurRatio || ratio;
  73290. // Set up assets
  73291. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73292. _this._createRandomTexture();
  73293. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73294. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73295. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73296. _this._createSSAOPostProcess(1.0);
  73297. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73298. _this._createSSAOCombinePostProcess(blurRatio);
  73299. // Set up pipeline
  73300. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73301. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73302. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73303. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73304. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73305. // Finish
  73306. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73307. if (cameras)
  73308. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73309. return _this;
  73310. }
  73311. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73312. get: function () {
  73313. return this._samples;
  73314. },
  73315. set: function (n) {
  73316. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73317. this._samples = n;
  73318. this._sampleSphere = this._generateHemisphere();
  73319. this._firstUpdate = true;
  73320. },
  73321. enumerable: true,
  73322. configurable: true
  73323. });
  73324. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73325. get: function () {
  73326. return this._expensiveBlur;
  73327. },
  73328. set: function (b) {
  73329. 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"]);
  73330. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73331. this._expensiveBlur = b;
  73332. this._firstUpdate = true;
  73333. },
  73334. enumerable: true,
  73335. configurable: true
  73336. });
  73337. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73338. /**
  73339. * Support test.
  73340. */
  73341. get: function () {
  73342. var engine = BABYLON.Engine.LastCreatedEngine;
  73343. if (!engine) {
  73344. return false;
  73345. }
  73346. return engine.getCaps().drawBuffersExtension;
  73347. },
  73348. enumerable: true,
  73349. configurable: true
  73350. });
  73351. // Public Methods
  73352. /**
  73353. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73354. */
  73355. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73356. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73357. for (var i = 0; i < this._scene.cameras.length; i++) {
  73358. var camera = this._scene.cameras[i];
  73359. this._originalColorPostProcess.dispose(camera);
  73360. this._ssaoPostProcess.dispose(camera);
  73361. this._blurHPostProcess.dispose(camera);
  73362. this._blurVPostProcess.dispose(camera);
  73363. this._ssaoCombinePostProcess.dispose(camera);
  73364. }
  73365. this._randomTexture.dispose();
  73366. if (disableGeometryBufferRenderer)
  73367. this._scene.disableGeometryBufferRenderer();
  73368. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73369. _super.prototype.dispose.call(this);
  73370. };
  73371. // Private Methods
  73372. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73373. var _this = this;
  73374. this._samplerOffsets = [];
  73375. var expensive = this.expensiveBlur;
  73376. for (var i = -8; i < 8; i++) {
  73377. this._samplerOffsets.push(i * 2 + 0.5);
  73378. }
  73379. 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");
  73380. this._blurHPostProcess.onApply = function (effect) {
  73381. if (!_this._scene.activeCamera) {
  73382. return;
  73383. }
  73384. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73385. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73386. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73387. effect.setFloat("radius", _this.radius);
  73388. effect.setTexture("depthSampler", _this._depthTexture);
  73389. if (_this._firstUpdate) {
  73390. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73391. }
  73392. };
  73393. 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");
  73394. this._blurVPostProcess.onApply = function (effect) {
  73395. if (!_this._scene.activeCamera) {
  73396. return;
  73397. }
  73398. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73399. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73400. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73401. effect.setFloat("radius", _this.radius);
  73402. effect.setTexture("depthSampler", _this._depthTexture);
  73403. if (_this._firstUpdate) {
  73404. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73405. _this._firstUpdate = false;
  73406. }
  73407. };
  73408. };
  73409. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73410. this._firstUpdate = true;
  73411. _super.prototype._rebuild.call(this);
  73412. };
  73413. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73414. var numSamples = this.samples;
  73415. var result = [];
  73416. var vector, scale;
  73417. var rand = function (min, max) {
  73418. return Math.random() * (max - min) + min;
  73419. };
  73420. var i = 0;
  73421. while (i < numSamples) {
  73422. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73423. vector.normalize();
  73424. scale = i / numSamples;
  73425. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73426. vector.scaleInPlace(scale);
  73427. result.push(vector.x, vector.y, vector.z);
  73428. i++;
  73429. }
  73430. return result;
  73431. };
  73432. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73433. var _this = this;
  73434. var numSamples = this.samples;
  73435. this._sampleSphere = this._generateHemisphere();
  73436. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73437. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73438. "base", "range", "projection", "near", "far", "texelSize",
  73439. "xViewport", "yViewport", "maxZ", "minZAspect"
  73440. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73441. this._ssaoPostProcess.onApply = function (effect) {
  73442. if (_this._firstUpdate) {
  73443. effect.setArray3("sampleSphere", _this._sampleSphere);
  73444. effect.setFloat("randTextureTiles", 4.0);
  73445. }
  73446. if (!_this._scene.activeCamera) {
  73447. return;
  73448. }
  73449. effect.setFloat("samplesFactor", 1 / _this.samples);
  73450. effect.setFloat("totalStrength", _this.totalStrength);
  73451. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73452. effect.setFloat("radius", _this.radius);
  73453. effect.setFloat("maxZ", _this.maxZ);
  73454. effect.setFloat("minZAspect", _this.minZAspect);
  73455. effect.setFloat("base", _this.base);
  73456. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73457. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73458. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73459. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73460. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73461. effect.setTexture("textureSampler", _this._depthTexture);
  73462. effect.setTexture("normalSampler", _this._normalTexture);
  73463. effect.setTexture("randomSampler", _this._randomTexture);
  73464. };
  73465. };
  73466. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73467. var _this = this;
  73468. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73469. this._ssaoCombinePostProcess.onApply = function (effect) {
  73470. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73471. };
  73472. };
  73473. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73474. var size = 512;
  73475. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73476. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73477. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73478. var context = this._randomTexture.getContext();
  73479. var rand = function (min, max) {
  73480. return Math.random() * (max - min) + min;
  73481. };
  73482. var randVector = BABYLON.Vector3.Zero();
  73483. for (var x = 0; x < size; x++) {
  73484. for (var y = 0; y < size; y++) {
  73485. randVector.x = rand(0.0, 1.0);
  73486. randVector.y = rand(0.0, 1.0);
  73487. randVector.z = 0.0;
  73488. randVector.normalize();
  73489. randVector.scaleInPlace(255);
  73490. randVector.x = Math.floor(randVector.x);
  73491. randVector.y = Math.floor(randVector.y);
  73492. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73493. context.fillRect(x, y, 1, 1);
  73494. }
  73495. }
  73496. this._randomTexture.update(false);
  73497. };
  73498. /**
  73499. * Serialize the rendering pipeline (Used when exporting)
  73500. * @returns the serialized object
  73501. */
  73502. SSAO2RenderingPipeline.prototype.serialize = function () {
  73503. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73504. serializationObject.customType = "SSAO2RenderingPipeline";
  73505. return serializationObject;
  73506. };
  73507. /**
  73508. * Parse the serialized pipeline
  73509. * @param source Source pipeline.
  73510. * @param scene The scene to load the pipeline to.
  73511. * @param rootUrl The URL of the serialized pipeline.
  73512. * @returns An instantiated pipeline from the serialized object.
  73513. */
  73514. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73515. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73516. };
  73517. __decorate([
  73518. BABYLON.serialize()
  73519. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73520. __decorate([
  73521. BABYLON.serialize()
  73522. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73523. __decorate([
  73524. BABYLON.serialize()
  73525. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73526. __decorate([
  73527. BABYLON.serialize("samples")
  73528. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73529. __decorate([
  73530. BABYLON.serialize()
  73531. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73532. __decorate([
  73533. BABYLON.serialize("expensiveBlur")
  73534. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73535. __decorate([
  73536. BABYLON.serialize()
  73537. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73538. __decorate([
  73539. BABYLON.serialize()
  73540. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73541. return SSAO2RenderingPipeline;
  73542. }(BABYLON.PostProcessRenderPipeline));
  73543. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73544. })(BABYLON || (BABYLON = {}));
  73545. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73546. // BABYLON.JS Chromatic Aberration GLSL Shader
  73547. // Author: Olivier Guyot
  73548. // Separates very slightly R, G and B colors on the edges of the screen
  73549. // Inspired by Francois Tarlier & Martins Upitis
  73550. var BABYLON;
  73551. (function (BABYLON) {
  73552. var LensRenderingPipeline = /** @class */ (function (_super) {
  73553. __extends(LensRenderingPipeline, _super);
  73554. /**
  73555. * @constructor
  73556. *
  73557. * Effect parameters are as follow:
  73558. * {
  73559. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73560. * edge_blur: number; // from 0 to x (1 for realism)
  73561. * distortion: number; // from 0 to x (1 for realism)
  73562. * grain_amount: number; // from 0 to 1
  73563. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73564. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73565. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73566. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73567. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73568. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73569. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73570. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73571. * }
  73572. * Note: if an effect parameter is unset, effect is disabled
  73573. *
  73574. * @param {string} name - The rendering pipeline name
  73575. * @param {object} parameters - An object containing all parameters (see above)
  73576. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73577. * @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)
  73578. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73579. */
  73580. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73581. if (ratio === void 0) { ratio = 1.0; }
  73582. var _this = _super.call(this, scene.getEngine(), name) || this;
  73583. // Lens effects can be of the following:
  73584. // - chromatic aberration (slight shift of RGB colors)
  73585. // - blur on the edge of the lens
  73586. // - lens distortion
  73587. // - depth-of-field blur & highlights enhancing
  73588. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73589. // - grain effect (noise or custom texture)
  73590. // Two additional texture samplers are needed:
  73591. // - depth map (for depth-of-field)
  73592. // - grain texture
  73593. /**
  73594. * The chromatic aberration PostProcess id in the pipeline
  73595. */
  73596. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73597. /**
  73598. * The highlights enhancing PostProcess id in the pipeline
  73599. */
  73600. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73601. /**
  73602. * The depth-of-field PostProcess id in the pipeline
  73603. */
  73604. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73605. _this._scene = scene;
  73606. // Fetch texture samplers
  73607. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73608. if (parameters.grain_texture) {
  73609. _this._grainTexture = parameters.grain_texture;
  73610. }
  73611. else {
  73612. _this._createGrainTexture();
  73613. }
  73614. // save parameters
  73615. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73616. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73617. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73618. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73619. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73620. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73621. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73622. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73623. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73624. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73625. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73626. // Create effects
  73627. _this._createChromaticAberrationPostProcess(ratio);
  73628. _this._createHighlightsPostProcess(ratio);
  73629. _this._createDepthOfFieldPostProcess(ratio / 4);
  73630. // Set up pipeline
  73631. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73632. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73633. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73634. if (_this._highlightsGain === -1) {
  73635. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73636. }
  73637. // Finish
  73638. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73639. if (cameras) {
  73640. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73641. }
  73642. return _this;
  73643. }
  73644. // public methods (self explanatory)
  73645. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73646. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73647. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73648. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73649. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73650. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73651. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73652. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73653. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73654. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73655. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73656. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73657. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73658. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73659. };
  73660. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73661. this._highlightsPostProcess.updateEffect();
  73662. };
  73663. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73664. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73665. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73666. this._highlightsGain = amount;
  73667. };
  73668. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73669. if (this._highlightsGain === -1) {
  73670. this._highlightsGain = 1.0;
  73671. }
  73672. this._highlightsThreshold = amount;
  73673. };
  73674. LensRenderingPipeline.prototype.disableHighlights = function () {
  73675. this._highlightsGain = -1;
  73676. };
  73677. /**
  73678. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73679. */
  73680. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73681. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73682. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73683. this._chromaticAberrationPostProcess = null;
  73684. this._highlightsPostProcess = null;
  73685. this._depthOfFieldPostProcess = null;
  73686. this._grainTexture.dispose();
  73687. if (disableDepthRender)
  73688. this._scene.disableDepthRenderer();
  73689. };
  73690. // colors shifting and distortion
  73691. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73692. var _this = this;
  73693. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73694. [], // samplers
  73695. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73696. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73697. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73698. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73699. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73700. effect.setFloat('radialIntensity', 1);
  73701. effect.setFloat2('direction', 17, 17);
  73702. effect.setFloat2('centerPosition', 0.5, 0.5);
  73703. };
  73704. };
  73705. // highlights enhancing
  73706. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73707. var _this = this;
  73708. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73709. [], // samplers
  73710. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73711. this._highlightsPostProcess.onApply = function (effect) {
  73712. effect.setFloat('gain', _this._highlightsGain);
  73713. effect.setFloat('threshold', _this._highlightsThreshold);
  73714. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73715. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73716. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73717. };
  73718. };
  73719. // colors shifting and distortion
  73720. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73721. var _this = this;
  73722. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73723. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73724. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73725. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73726. this._depthOfFieldPostProcess.onApply = function (effect) {
  73727. effect.setTexture("depthSampler", _this._depthTexture);
  73728. effect.setTexture("grainSampler", _this._grainTexture);
  73729. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73730. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73731. effect.setFloat('grain_amount', _this._grainAmount);
  73732. effect.setBool('blur_noise', _this._blurNoise);
  73733. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73734. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73735. effect.setFloat('distortion', _this._distortion);
  73736. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73737. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73738. effect.setFloat('aperture', _this._dofAperture);
  73739. effect.setFloat('darken', _this._dofDarken);
  73740. effect.setFloat('edge_blur', _this._edgeBlur);
  73741. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73742. if (_this._scene.activeCamera) {
  73743. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73744. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73745. }
  73746. };
  73747. };
  73748. // creates a black and white random noise texture, 512x512
  73749. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73750. var size = 512;
  73751. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73752. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73753. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73754. var context = this._grainTexture.getContext();
  73755. var rand = function (min, max) {
  73756. return Math.random() * (max - min) + min;
  73757. };
  73758. var value;
  73759. for (var x = 0; x < size; x++) {
  73760. for (var y = 0; y < size; y++) {
  73761. value = Math.floor(rand(0.42, 0.58) * 255);
  73762. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73763. context.fillRect(x, y, 1, 1);
  73764. }
  73765. }
  73766. this._grainTexture.update(false);
  73767. };
  73768. return LensRenderingPipeline;
  73769. }(BABYLON.PostProcessRenderPipeline));
  73770. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73771. })(BABYLON || (BABYLON = {}));
  73772. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73773. var BABYLON;
  73774. (function (BABYLON) {
  73775. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73776. __extends(StandardRenderingPipeline, _super);
  73777. /**
  73778. * @constructor
  73779. * @param {string} name - The rendering pipeline name
  73780. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73781. * @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)
  73782. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73783. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73784. */
  73785. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73786. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73787. var _this = _super.call(this, scene.getEngine(), name) || this;
  73788. _this.downSampleX4PostProcess = null;
  73789. _this.brightPassPostProcess = null;
  73790. _this.blurHPostProcesses = [];
  73791. _this.blurVPostProcesses = [];
  73792. _this.textureAdderPostProcess = null;
  73793. _this.volumetricLightPostProcess = null;
  73794. _this.volumetricLightSmoothXPostProcess = null;
  73795. _this.volumetricLightSmoothYPostProcess = null;
  73796. _this.volumetricLightMergePostProces = null;
  73797. _this.volumetricLightFinalPostProcess = null;
  73798. _this.luminancePostProcess = null;
  73799. _this.luminanceDownSamplePostProcesses = [];
  73800. _this.hdrPostProcess = null;
  73801. _this.textureAdderFinalPostProcess = null;
  73802. _this.lensFlareFinalPostProcess = null;
  73803. _this.hdrFinalPostProcess = null;
  73804. _this.lensFlarePostProcess = null;
  73805. _this.lensFlareComposePostProcess = null;
  73806. _this.motionBlurPostProcess = null;
  73807. _this.depthOfFieldPostProcess = null;
  73808. // Values
  73809. _this.brightThreshold = 1.0;
  73810. _this.blurWidth = 512.0;
  73811. _this.horizontalBlur = false;
  73812. _this.exposure = 1.0;
  73813. _this.lensTexture = null;
  73814. _this.volumetricLightCoefficient = 0.2;
  73815. _this.volumetricLightPower = 4.0;
  73816. _this.volumetricLightBlurScale = 64.0;
  73817. _this.sourceLight = null;
  73818. _this.hdrMinimumLuminance = 1.0;
  73819. _this.hdrDecreaseRate = 0.5;
  73820. _this.hdrIncreaseRate = 0.5;
  73821. _this.lensColorTexture = null;
  73822. _this.lensFlareStrength = 20.0;
  73823. _this.lensFlareGhostDispersal = 1.4;
  73824. _this.lensFlareHaloWidth = 0.7;
  73825. _this.lensFlareDistortionStrength = 16.0;
  73826. _this.lensStarTexture = null;
  73827. _this.lensFlareDirtTexture = null;
  73828. _this.depthOfFieldDistance = 10.0;
  73829. _this.depthOfFieldBlurWidth = 64.0;
  73830. _this.motionStrength = 1.0;
  73831. // IAnimatable
  73832. _this.animations = [];
  73833. _this._currentDepthOfFieldSource = null;
  73834. _this._hdrCurrentLuminance = 1.0;
  73835. // Getters and setters
  73836. _this._bloomEnabled = true;
  73837. _this._depthOfFieldEnabled = false;
  73838. _this._vlsEnabled = false;
  73839. _this._lensFlareEnabled = false;
  73840. _this._hdrEnabled = false;
  73841. _this._motionBlurEnabled = false;
  73842. _this._motionBlurSamples = 64.0;
  73843. _this._volumetricLightStepsCount = 50.0;
  73844. _this._cameras = cameras || [];
  73845. // Initialize
  73846. _this._scene = scene;
  73847. _this._basePostProcess = originalPostProcess;
  73848. _this._ratio = ratio;
  73849. // Misc
  73850. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73851. // Finish
  73852. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73853. _this._buildPipeline();
  73854. return _this;
  73855. }
  73856. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73857. get: function () {
  73858. return this._bloomEnabled;
  73859. },
  73860. set: function (enabled) {
  73861. if (this._bloomEnabled === enabled) {
  73862. return;
  73863. }
  73864. this._bloomEnabled = enabled;
  73865. this._buildPipeline();
  73866. },
  73867. enumerable: true,
  73868. configurable: true
  73869. });
  73870. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73871. get: function () {
  73872. return this._depthOfFieldEnabled;
  73873. },
  73874. set: function (enabled) {
  73875. if (this._depthOfFieldEnabled === enabled) {
  73876. return;
  73877. }
  73878. this._depthOfFieldEnabled = enabled;
  73879. this._buildPipeline();
  73880. },
  73881. enumerable: true,
  73882. configurable: true
  73883. });
  73884. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73885. get: function () {
  73886. return this._lensFlareEnabled;
  73887. },
  73888. set: function (enabled) {
  73889. if (this._lensFlareEnabled === enabled) {
  73890. return;
  73891. }
  73892. this._lensFlareEnabled = enabled;
  73893. this._buildPipeline();
  73894. },
  73895. enumerable: true,
  73896. configurable: true
  73897. });
  73898. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73899. get: function () {
  73900. return this._hdrEnabled;
  73901. },
  73902. set: function (enabled) {
  73903. if (this._hdrEnabled === enabled) {
  73904. return;
  73905. }
  73906. this._hdrEnabled = enabled;
  73907. this._buildPipeline();
  73908. },
  73909. enumerable: true,
  73910. configurable: true
  73911. });
  73912. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73913. get: function () {
  73914. return this._vlsEnabled;
  73915. },
  73916. set: function (enabled) {
  73917. if (this._vlsEnabled === enabled) {
  73918. return;
  73919. }
  73920. if (enabled) {
  73921. var geometry = this._scene.enableGeometryBufferRenderer();
  73922. if (!geometry) {
  73923. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73924. return;
  73925. }
  73926. }
  73927. this._vlsEnabled = enabled;
  73928. this._buildPipeline();
  73929. },
  73930. enumerable: true,
  73931. configurable: true
  73932. });
  73933. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73934. get: function () {
  73935. return this._motionBlurEnabled;
  73936. },
  73937. set: function (enabled) {
  73938. if (this._motionBlurEnabled === enabled) {
  73939. return;
  73940. }
  73941. this._motionBlurEnabled = enabled;
  73942. this._buildPipeline();
  73943. },
  73944. enumerable: true,
  73945. configurable: true
  73946. });
  73947. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73948. get: function () {
  73949. return this._volumetricLightStepsCount;
  73950. },
  73951. set: function (count) {
  73952. if (this.volumetricLightPostProcess) {
  73953. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73954. }
  73955. this._volumetricLightStepsCount = count;
  73956. },
  73957. enumerable: true,
  73958. configurable: true
  73959. });
  73960. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73961. get: function () {
  73962. return this._motionBlurSamples;
  73963. },
  73964. set: function (samples) {
  73965. if (this.motionBlurPostProcess) {
  73966. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73967. }
  73968. this._motionBlurSamples = samples;
  73969. },
  73970. enumerable: true,
  73971. configurable: true
  73972. });
  73973. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73974. var _this = this;
  73975. var ratio = this._ratio;
  73976. var scene = this._scene;
  73977. this._disposePostProcesses();
  73978. this._reset();
  73979. // Create pass post-process
  73980. if (!this._basePostProcess) {
  73981. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73982. this.originalPostProcess.onApply = function (effect) {
  73983. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73984. };
  73985. }
  73986. else {
  73987. this.originalPostProcess = this._basePostProcess;
  73988. }
  73989. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73990. this._currentDepthOfFieldSource = this.originalPostProcess;
  73991. if (this._bloomEnabled) {
  73992. // Create down sample X4 post-process
  73993. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73994. // Create bright pass post-process
  73995. this._createBrightPassPostProcess(scene, ratio / 2);
  73996. // Create gaussian blur post-processes (down sampling blurs)
  73997. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73998. // Create texture adder post-process
  73999. this._createTextureAdderPostProcess(scene, ratio);
  74000. // Create depth-of-field source post-process
  74001. 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);
  74002. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74003. }
  74004. if (this._vlsEnabled) {
  74005. // Create volumetric light
  74006. this._createVolumetricLightPostProcess(scene, ratio);
  74007. // Create volumetric light final post-process
  74008. 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);
  74009. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74010. }
  74011. if (this._lensFlareEnabled) {
  74012. // Create lens flare post-process
  74013. this._createLensFlarePostProcess(scene, ratio);
  74014. // Create depth-of-field source post-process post lens-flare and disable it now
  74015. 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);
  74016. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74017. }
  74018. if (this._hdrEnabled) {
  74019. // Create luminance
  74020. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74021. // Create HDR
  74022. this._createHdrPostProcess(scene, ratio);
  74023. // Create depth-of-field source post-process post hdr and disable it now
  74024. 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);
  74025. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74026. }
  74027. if (this._depthOfFieldEnabled) {
  74028. // Create gaussian blur used by depth-of-field
  74029. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74030. // Create depth-of-field post-process
  74031. this._createDepthOfFieldPostProcess(scene, ratio);
  74032. }
  74033. if (this._motionBlurEnabled) {
  74034. // Create motion blur post-process
  74035. this._createMotionBlurPostProcess(scene, ratio);
  74036. }
  74037. if (this._cameras !== null) {
  74038. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74039. }
  74040. };
  74041. // Down Sample X4 Post-Processs
  74042. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74043. var _this = this;
  74044. var downSampleX4Offsets = new Array(32);
  74045. 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);
  74046. this.downSampleX4PostProcess.onApply = function (effect) {
  74047. var id = 0;
  74048. var width = _this.downSampleX4PostProcess.width;
  74049. var height = _this.downSampleX4PostProcess.height;
  74050. for (var i = -2; i < 2; i++) {
  74051. for (var j = -2; j < 2; j++) {
  74052. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74053. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74054. id += 2;
  74055. }
  74056. }
  74057. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74058. };
  74059. // Add to pipeline
  74060. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74061. };
  74062. // Brightpass Post-Process
  74063. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74064. var _this = this;
  74065. var brightOffsets = new Array(8);
  74066. 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);
  74067. this.brightPassPostProcess.onApply = function (effect) {
  74068. var sU = (1.0 / _this.brightPassPostProcess.width);
  74069. var sV = (1.0 / _this.brightPassPostProcess.height);
  74070. brightOffsets[0] = -0.5 * sU;
  74071. brightOffsets[1] = 0.5 * sV;
  74072. brightOffsets[2] = 0.5 * sU;
  74073. brightOffsets[3] = 0.5 * sV;
  74074. brightOffsets[4] = -0.5 * sU;
  74075. brightOffsets[5] = -0.5 * sV;
  74076. brightOffsets[6] = 0.5 * sU;
  74077. brightOffsets[7] = -0.5 * sV;
  74078. effect.setArray2("dsOffsets", brightOffsets);
  74079. effect.setFloat("brightThreshold", _this.brightThreshold);
  74080. };
  74081. // Add to pipeline
  74082. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74083. };
  74084. // Create blur H&V post-processes
  74085. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74086. var _this = this;
  74087. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74088. var engine = scene.getEngine();
  74089. 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);
  74090. 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);
  74091. blurX.onActivateObservable.add(function () {
  74092. var dw = blurX.width / engine.getRenderWidth();
  74093. blurX.kernel = _this[blurWidthKey] * dw;
  74094. });
  74095. blurY.onActivateObservable.add(function () {
  74096. var dw = blurY.height / engine.getRenderHeight();
  74097. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74098. });
  74099. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74100. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74101. this.blurHPostProcesses.push(blurX);
  74102. this.blurVPostProcesses.push(blurY);
  74103. };
  74104. // Create texture adder post-process
  74105. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74106. var _this = this;
  74107. 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);
  74108. this.textureAdderPostProcess.onApply = function (effect) {
  74109. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74110. effect.setTexture("lensSampler", _this.lensTexture);
  74111. effect.setFloat("exposure", _this.exposure);
  74112. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74113. };
  74114. // Add to pipeline
  74115. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74116. };
  74117. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74118. var _this = this;
  74119. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74120. geometryRenderer.enablePosition = true;
  74121. var geometry = geometryRenderer.getGBuffer();
  74122. // Base post-process
  74123. 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));
  74124. var depthValues = BABYLON.Vector2.Zero();
  74125. this.volumetricLightPostProcess.onApply = function (effect) {
  74126. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74127. var generator = _this.sourceLight.getShadowGenerator();
  74128. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74129. effect.setTexture("positionSampler", geometry.textures[2]);
  74130. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74131. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74132. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74133. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74134. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74135. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74136. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74137. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74138. effect.setVector2("depthValues", depthValues);
  74139. }
  74140. };
  74141. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74142. // Smooth
  74143. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74144. // Merge
  74145. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74146. this.volumetricLightMergePostProces.onApply = function (effect) {
  74147. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74148. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74149. };
  74150. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74151. };
  74152. // Create luminance
  74153. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74154. var _this = this;
  74155. // Create luminance
  74156. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74157. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74158. var offsets = [];
  74159. this.luminancePostProcess.onApply = function (effect) {
  74160. var sU = (1.0 / _this.luminancePostProcess.width);
  74161. var sV = (1.0 / _this.luminancePostProcess.height);
  74162. offsets[0] = -0.5 * sU;
  74163. offsets[1] = 0.5 * sV;
  74164. offsets[2] = 0.5 * sU;
  74165. offsets[3] = 0.5 * sV;
  74166. offsets[4] = -0.5 * sU;
  74167. offsets[5] = -0.5 * sV;
  74168. offsets[6] = 0.5 * sU;
  74169. offsets[7] = -0.5 * sV;
  74170. effect.setArray2("lumOffsets", offsets);
  74171. };
  74172. // Add to pipeline
  74173. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74174. // Create down sample luminance
  74175. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74176. var size = Math.pow(3, i);
  74177. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74178. if (i === 0) {
  74179. defines += "#define FINAL_DOWN_SAMPLER";
  74180. }
  74181. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74182. this.luminanceDownSamplePostProcesses.push(postProcess);
  74183. }
  74184. // Create callbacks and add effects
  74185. var lastLuminance = this.luminancePostProcess;
  74186. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74187. var downSampleOffsets = new Array(18);
  74188. pp.onApply = function (effect) {
  74189. if (!lastLuminance) {
  74190. return;
  74191. }
  74192. var id = 0;
  74193. for (var x = -1; x < 2; x++) {
  74194. for (var y = -1; y < 2; y++) {
  74195. downSampleOffsets[id] = x / lastLuminance.width;
  74196. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74197. id += 2;
  74198. }
  74199. }
  74200. effect.setArray2("dsOffsets", downSampleOffsets);
  74201. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74202. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74203. lastLuminance = _this.luminancePostProcess;
  74204. }
  74205. else {
  74206. lastLuminance = pp;
  74207. }
  74208. };
  74209. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74210. pp.onAfterRender = function (effect) {
  74211. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74212. 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);
  74213. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74214. };
  74215. }
  74216. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74217. });
  74218. };
  74219. // Create HDR post-process
  74220. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74221. var _this = this;
  74222. 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);
  74223. var outputLiminance = 1;
  74224. var time = 0;
  74225. var lastTime = 0;
  74226. this.hdrPostProcess.onApply = function (effect) {
  74227. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74228. time += scene.getEngine().getDeltaTime();
  74229. if (outputLiminance < 0) {
  74230. outputLiminance = _this._hdrCurrentLuminance;
  74231. }
  74232. else {
  74233. var dt = (lastTime - time) / 1000.0;
  74234. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74235. outputLiminance += _this.hdrDecreaseRate * dt;
  74236. }
  74237. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74238. outputLiminance -= _this.hdrIncreaseRate * dt;
  74239. }
  74240. else {
  74241. outputLiminance = _this._hdrCurrentLuminance;
  74242. }
  74243. }
  74244. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74245. effect.setFloat("averageLuminance", outputLiminance);
  74246. lastTime = time;
  74247. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74248. };
  74249. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74250. };
  74251. // Create lens flare post-process
  74252. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74253. var _this = this;
  74254. 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);
  74255. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74256. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74257. 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);
  74258. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74259. var resolution = new BABYLON.Vector2(0, 0);
  74260. // Lens flare
  74261. this.lensFlarePostProcess.onApply = function (effect) {
  74262. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74263. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74264. effect.setFloat("strength", _this.lensFlareStrength);
  74265. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74266. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74267. // Shift
  74268. resolution.x = _this.lensFlarePostProcess.width;
  74269. resolution.y = _this.lensFlarePostProcess.height;
  74270. effect.setVector2("resolution", resolution);
  74271. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74272. };
  74273. // Compose
  74274. 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);
  74275. 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);
  74276. this.lensFlareComposePostProcess.onApply = function (effect) {
  74277. if (!_this._scene.activeCamera) {
  74278. return;
  74279. }
  74280. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74281. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74282. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74283. // Lens start rotation matrix
  74284. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74285. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74286. 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));
  74287. camRot *= 4.0;
  74288. 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);
  74289. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74290. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74291. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74292. };
  74293. };
  74294. // Create depth-of-field post-process
  74295. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74296. var _this = this;
  74297. 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);
  74298. this.depthOfFieldPostProcess.onApply = function (effect) {
  74299. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74300. effect.setTexture("depthSampler", _this._getDepthTexture());
  74301. effect.setFloat("distance", _this.depthOfFieldDistance);
  74302. };
  74303. // Add to pipeline
  74304. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74305. };
  74306. // Create motion blur post-process
  74307. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74308. var _this = this;
  74309. 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);
  74310. var motionScale = 0;
  74311. var prevViewProjection = BABYLON.Matrix.Identity();
  74312. var invViewProjection = BABYLON.Matrix.Identity();
  74313. var viewProjection = BABYLON.Matrix.Identity();
  74314. var screenSize = BABYLON.Vector2.Zero();
  74315. this.motionBlurPostProcess.onApply = function (effect) {
  74316. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74317. viewProjection.invertToRef(invViewProjection);
  74318. effect.setMatrix("inverseViewProjection", invViewProjection);
  74319. effect.setMatrix("prevViewProjection", prevViewProjection);
  74320. prevViewProjection = viewProjection;
  74321. screenSize.x = _this.motionBlurPostProcess.width;
  74322. screenSize.y = _this.motionBlurPostProcess.height;
  74323. effect.setVector2("screenSize", screenSize);
  74324. motionScale = scene.getEngine().getFps() / 60.0;
  74325. effect.setFloat("motionScale", motionScale);
  74326. effect.setFloat("motionStrength", _this.motionStrength);
  74327. effect.setTexture("depthSampler", _this._getDepthTexture());
  74328. };
  74329. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74330. };
  74331. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74332. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74333. var renderer = this._scene.enableGeometryBufferRenderer();
  74334. return renderer.getGBuffer().textures[0];
  74335. }
  74336. return this._scene.enableDepthRenderer().getDepthMap();
  74337. };
  74338. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74339. for (var i = 0; i < this._cameras.length; i++) {
  74340. var camera = this._cameras[i];
  74341. if (this.originalPostProcess) {
  74342. this.originalPostProcess.dispose(camera);
  74343. }
  74344. if (this.downSampleX4PostProcess) {
  74345. this.downSampleX4PostProcess.dispose(camera);
  74346. }
  74347. if (this.brightPassPostProcess) {
  74348. this.brightPassPostProcess.dispose(camera);
  74349. }
  74350. if (this.textureAdderPostProcess) {
  74351. this.textureAdderPostProcess.dispose(camera);
  74352. }
  74353. if (this.textureAdderFinalPostProcess) {
  74354. this.textureAdderFinalPostProcess.dispose(camera);
  74355. }
  74356. if (this.volumetricLightPostProcess) {
  74357. this.volumetricLightPostProcess.dispose(camera);
  74358. }
  74359. if (this.volumetricLightSmoothXPostProcess) {
  74360. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74361. }
  74362. if (this.volumetricLightSmoothYPostProcess) {
  74363. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74364. }
  74365. if (this.volumetricLightMergePostProces) {
  74366. this.volumetricLightMergePostProces.dispose(camera);
  74367. }
  74368. if (this.volumetricLightFinalPostProcess) {
  74369. this.volumetricLightFinalPostProcess.dispose(camera);
  74370. }
  74371. if (this.lensFlarePostProcess) {
  74372. this.lensFlarePostProcess.dispose(camera);
  74373. }
  74374. if (this.lensFlareComposePostProcess) {
  74375. this.lensFlareComposePostProcess.dispose(camera);
  74376. }
  74377. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74378. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74379. }
  74380. if (this.luminancePostProcess) {
  74381. this.luminancePostProcess.dispose(camera);
  74382. }
  74383. if (this.hdrPostProcess) {
  74384. this.hdrPostProcess.dispose(camera);
  74385. }
  74386. if (this.hdrFinalPostProcess) {
  74387. this.hdrFinalPostProcess.dispose(camera);
  74388. }
  74389. if (this.depthOfFieldPostProcess) {
  74390. this.depthOfFieldPostProcess.dispose(camera);
  74391. }
  74392. if (this.motionBlurPostProcess) {
  74393. this.motionBlurPostProcess.dispose(camera);
  74394. }
  74395. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74396. this.blurHPostProcesses[j].dispose(camera);
  74397. }
  74398. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74399. this.blurVPostProcesses[j].dispose(camera);
  74400. }
  74401. }
  74402. this.originalPostProcess = null;
  74403. this.downSampleX4PostProcess = null;
  74404. this.brightPassPostProcess = null;
  74405. this.textureAdderPostProcess = null;
  74406. this.textureAdderFinalPostProcess = null;
  74407. this.volumetricLightPostProcess = null;
  74408. this.volumetricLightSmoothXPostProcess = null;
  74409. this.volumetricLightSmoothYPostProcess = null;
  74410. this.volumetricLightMergePostProces = null;
  74411. this.volumetricLightFinalPostProcess = null;
  74412. this.lensFlarePostProcess = null;
  74413. this.lensFlareComposePostProcess = null;
  74414. this.luminancePostProcess = null;
  74415. this.hdrPostProcess = null;
  74416. this.hdrFinalPostProcess = null;
  74417. this.depthOfFieldPostProcess = null;
  74418. this.motionBlurPostProcess = null;
  74419. this.luminanceDownSamplePostProcesses = [];
  74420. this.blurHPostProcesses = [];
  74421. this.blurVPostProcesses = [];
  74422. };
  74423. /**
  74424. * Dispose of the pipeline and stop all post processes
  74425. */
  74426. StandardRenderingPipeline.prototype.dispose = function () {
  74427. this._disposePostProcesses();
  74428. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74429. _super.prototype.dispose.call(this);
  74430. };
  74431. /**
  74432. * Serialize the rendering pipeline (Used when exporting)
  74433. * @returns the serialized object
  74434. */
  74435. StandardRenderingPipeline.prototype.serialize = function () {
  74436. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74437. if (this.sourceLight) {
  74438. serializationObject.sourceLightId = this.sourceLight.id;
  74439. }
  74440. serializationObject.customType = "StandardRenderingPipeline";
  74441. return serializationObject;
  74442. };
  74443. /**
  74444. * Parse the serialized pipeline
  74445. * @param source Source pipeline.
  74446. * @param scene The scene to load the pipeline to.
  74447. * @param rootUrl The URL of the serialized pipeline.
  74448. * @returns An instantiated pipeline from the serialized object.
  74449. */
  74450. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74451. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74452. if (source.sourceLightId) {
  74453. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74454. }
  74455. return p;
  74456. };
  74457. // Luminance steps
  74458. StandardRenderingPipeline.LuminanceSteps = 6;
  74459. __decorate([
  74460. BABYLON.serialize()
  74461. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74462. __decorate([
  74463. BABYLON.serialize()
  74464. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74465. __decorate([
  74466. BABYLON.serialize()
  74467. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74468. __decorate([
  74469. BABYLON.serialize()
  74470. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74471. __decorate([
  74472. BABYLON.serializeAsTexture("lensTexture")
  74473. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74474. __decorate([
  74475. BABYLON.serialize()
  74476. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74477. __decorate([
  74478. BABYLON.serialize()
  74479. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74480. __decorate([
  74481. BABYLON.serialize()
  74482. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74483. __decorate([
  74484. BABYLON.serialize()
  74485. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74486. __decorate([
  74487. BABYLON.serialize()
  74488. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74489. __decorate([
  74490. BABYLON.serialize()
  74491. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74492. __decorate([
  74493. BABYLON.serializeAsTexture("lensColorTexture")
  74494. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74495. __decorate([
  74496. BABYLON.serialize()
  74497. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74498. __decorate([
  74499. BABYLON.serialize()
  74500. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74501. __decorate([
  74502. BABYLON.serialize()
  74503. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74504. __decorate([
  74505. BABYLON.serialize()
  74506. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74507. __decorate([
  74508. BABYLON.serializeAsTexture("lensStarTexture")
  74509. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74510. __decorate([
  74511. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74512. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74513. __decorate([
  74514. BABYLON.serialize()
  74515. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74516. __decorate([
  74517. BABYLON.serialize()
  74518. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74519. __decorate([
  74520. BABYLON.serialize()
  74521. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74522. __decorate([
  74523. BABYLON.serialize()
  74524. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74525. __decorate([
  74526. BABYLON.serialize()
  74527. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74528. __decorate([
  74529. BABYLON.serialize()
  74530. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74531. __decorate([
  74532. BABYLON.serialize()
  74533. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74534. __decorate([
  74535. BABYLON.serialize()
  74536. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74537. __decorate([
  74538. BABYLON.serialize()
  74539. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74540. __decorate([
  74541. BABYLON.serialize()
  74542. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74543. __decorate([
  74544. BABYLON.serialize()
  74545. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74546. __decorate([
  74547. BABYLON.serialize()
  74548. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74549. return StandardRenderingPipeline;
  74550. }(BABYLON.PostProcessRenderPipeline));
  74551. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74552. })(BABYLON || (BABYLON = {}));
  74553. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74554. var BABYLON;
  74555. (function (BABYLON) {
  74556. var FxaaPostProcess = /** @class */ (function (_super) {
  74557. __extends(FxaaPostProcess, _super);
  74558. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74559. if (camera === void 0) { camera = null; }
  74560. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74561. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74562. var defines = _this._getDefines();
  74563. _this.updateEffect(defines);
  74564. _this.onApplyObservable.add(function (effect) {
  74565. var texelSize = _this.texelSize;
  74566. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74567. });
  74568. return _this;
  74569. }
  74570. FxaaPostProcess.prototype._getDefines = function () {
  74571. var engine = this.getEngine();
  74572. if (!engine) {
  74573. return null;
  74574. }
  74575. var glInfo = engine.getGlInfo();
  74576. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74577. return "#define MALI 1\n";
  74578. }
  74579. return null;
  74580. };
  74581. return FxaaPostProcess;
  74582. }(BABYLON.PostProcess));
  74583. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74584. })(BABYLON || (BABYLON = {}));
  74585. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74586. var BABYLON;
  74587. (function (BABYLON) {
  74588. /**
  74589. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74590. */
  74591. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74592. __extends(ChromaticAberrationPostProcess, _super);
  74593. /**
  74594. * Creates a new instance ChromaticAberrationPostProcess
  74595. * @param name The name of the effect.
  74596. * @param screenWidth The width of the screen to apply the effect on.
  74597. * @param screenHeight The height of the screen to apply the effect on.
  74598. * @param options The required width/height ratio to downsize to before computing the render pass.
  74599. * @param camera The camera to apply the render pass to.
  74600. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74601. * @param engine The engine which the post process will be applied. (default: current engine)
  74602. * @param reusable If the post process can be reused on the same frame. (default: false)
  74603. * @param textureType Type of textures used when performing the post process. (default: 0)
  74604. * @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)
  74605. */
  74606. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74607. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74608. if (blockCompilation === void 0) { blockCompilation = false; }
  74609. 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;
  74610. /**
  74611. * The amount of seperation of rgb channels (default: 30)
  74612. */
  74613. _this.aberrationAmount = 30;
  74614. /**
  74615. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74616. */
  74617. _this.radialIntensity = 0;
  74618. /**
  74619. * 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))
  74620. */
  74621. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74622. /**
  74623. * 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))
  74624. */
  74625. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74626. _this.onApplyObservable.add(function (effect) {
  74627. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74628. effect.setFloat('screen_width', screenWidth);
  74629. effect.setFloat('screen_height', screenHeight);
  74630. effect.setFloat('radialIntensity', _this.radialIntensity);
  74631. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74632. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74633. });
  74634. return _this;
  74635. }
  74636. return ChromaticAberrationPostProcess;
  74637. }(BABYLON.PostProcess));
  74638. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74639. })(BABYLON || (BABYLON = {}));
  74640. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74641. var BABYLON;
  74642. (function (BABYLON) {
  74643. /**
  74644. * The GrainPostProcess adds noise to the image at mid luminance levels
  74645. */
  74646. var GrainPostProcess = /** @class */ (function (_super) {
  74647. __extends(GrainPostProcess, _super);
  74648. /**
  74649. * Creates a new instance of @see GrainPostProcess
  74650. * @param name The name of the effect.
  74651. * @param options The required width/height ratio to downsize to before computing the render pass.
  74652. * @param camera The camera to apply the render pass to.
  74653. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74654. * @param engine The engine which the post process will be applied. (default: current engine)
  74655. * @param reusable If the post process can be reused on the same frame. (default: false)
  74656. * @param textureType Type of textures used when performing the post process. (default: 0)
  74657. * @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)
  74658. */
  74659. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74660. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74661. if (blockCompilation === void 0) { blockCompilation = false; }
  74662. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74663. /**
  74664. * The intensity of the grain added (default: 30)
  74665. */
  74666. _this.intensity = 30;
  74667. /**
  74668. * If the grain should be randomized on every frame
  74669. */
  74670. _this.animated = false;
  74671. _this.onApplyObservable.add(function (effect) {
  74672. effect.setFloat('intensity', _this.intensity);
  74673. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74674. });
  74675. return _this;
  74676. }
  74677. return GrainPostProcess;
  74678. }(BABYLON.PostProcess));
  74679. BABYLON.GrainPostProcess = GrainPostProcess;
  74680. })(BABYLON || (BABYLON = {}));
  74681. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74682. var BABYLON;
  74683. (function (BABYLON) {
  74684. /**
  74685. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74686. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74687. */
  74688. var SharpenPostProcess = /** @class */ (function (_super) {
  74689. __extends(SharpenPostProcess, _super);
  74690. /**
  74691. * Creates a new instance ConvolutionPostProcess
  74692. * @param name The name of the effect.
  74693. * @param options The required width/height ratio to downsize to before computing the render pass.
  74694. * @param camera The camera to apply the render pass to.
  74695. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74696. * @param engine The engine which the post process will be applied. (default: current engine)
  74697. * @param reusable If the post process can be reused on the same frame. (default: false)
  74698. * @param textureType Type of textures used when performing the post process. (default: 0)
  74699. * @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)
  74700. */
  74701. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74702. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74703. if (blockCompilation === void 0) { blockCompilation = false; }
  74704. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74705. /**
  74706. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74707. */
  74708. _this.colorAmount = 1.0;
  74709. /**
  74710. * How much sharpness should be applied (default: 0.3)
  74711. */
  74712. _this.edgeAmount = 0.3;
  74713. _this.onApply = function (effect) {
  74714. effect.setFloat2("screenSize", _this.width, _this.height);
  74715. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74716. };
  74717. return _this;
  74718. }
  74719. return SharpenPostProcess;
  74720. }(BABYLON.PostProcess));
  74721. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74722. })(BABYLON || (BABYLON = {}));
  74723. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74724. var BABYLON;
  74725. (function (BABYLON) {
  74726. /**
  74727. * The Blur Post Process which blurs an image based on a kernel and direction.
  74728. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74729. */
  74730. var BlurPostProcess = /** @class */ (function (_super) {
  74731. __extends(BlurPostProcess, _super);
  74732. /**
  74733. * Creates a new instance BlurPostProcess
  74734. * @param name The name of the effect.
  74735. * @param direction The direction in which to blur the image.
  74736. * @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.
  74737. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74738. * @param camera The camera to apply the render pass to.
  74739. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74740. * @param engine The engine which the post process will be applied. (default: current engine)
  74741. * @param reusable If the post process can be reused on the same frame. (default: false)
  74742. * @param textureType Type of textures used when performing the post process. (default: 0)
  74743. * @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)
  74744. */
  74745. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74746. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74747. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74748. if (defines === void 0) { defines = ""; }
  74749. if (blockCompilation === void 0) { blockCompilation = false; }
  74750. 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;
  74751. _this.direction = direction;
  74752. _this.blockCompilation = blockCompilation;
  74753. _this._packedFloat = false;
  74754. _this._staticDefines = "";
  74755. _this._staticDefines = defines;
  74756. _this.onApplyObservable.add(function (effect) {
  74757. if (_this._outputTexture) {
  74758. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74759. }
  74760. else {
  74761. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74762. }
  74763. });
  74764. _this.kernel = kernel;
  74765. return _this;
  74766. }
  74767. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74768. /**
  74769. * Gets the length in pixels of the blur sample region
  74770. */
  74771. get: function () {
  74772. return this._idealKernel;
  74773. },
  74774. /**
  74775. * Sets the length in pixels of the blur sample region
  74776. */
  74777. set: function (v) {
  74778. if (this._idealKernel === v) {
  74779. return;
  74780. }
  74781. v = Math.max(v, 1);
  74782. this._idealKernel = v;
  74783. this._kernel = this._nearestBestKernel(v);
  74784. if (!this.blockCompilation) {
  74785. this._updateParameters();
  74786. }
  74787. },
  74788. enumerable: true,
  74789. configurable: true
  74790. });
  74791. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74792. /**
  74793. * Gets wether or not the blur is unpacking/repacking floats
  74794. */
  74795. get: function () {
  74796. return this._packedFloat;
  74797. },
  74798. /**
  74799. * Sets wether or not the blur needs to unpack/repack floats
  74800. */
  74801. set: function (v) {
  74802. if (this._packedFloat === v) {
  74803. return;
  74804. }
  74805. this._packedFloat = v;
  74806. if (!this.blockCompilation) {
  74807. this._updateParameters();
  74808. }
  74809. },
  74810. enumerable: true,
  74811. configurable: true
  74812. });
  74813. /**
  74814. * Updates the effect with the current post process compile time values and recompiles the shader.
  74815. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74816. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74817. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74818. * @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
  74819. * @param onCompiled Called when the shader has been compiled.
  74820. * @param onError Called if there is an error when compiling a shader.
  74821. */
  74822. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74823. if (defines === void 0) { defines = null; }
  74824. if (uniforms === void 0) { uniforms = null; }
  74825. if (samplers === void 0) { samplers = null; }
  74826. this._updateParameters(onCompiled, onError);
  74827. };
  74828. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74829. // Generate sampling offsets and weights
  74830. var N = this._kernel;
  74831. var centerIndex = (N - 1) / 2;
  74832. // Generate Gaussian sampling weights over kernel
  74833. var offsets = [];
  74834. var weights = [];
  74835. var totalWeight = 0;
  74836. for (var i = 0; i < N; i++) {
  74837. var u = i / (N - 1);
  74838. var w = this._gaussianWeight(u * 2.0 - 1);
  74839. offsets[i] = (i - centerIndex);
  74840. weights[i] = w;
  74841. totalWeight += w;
  74842. }
  74843. // Normalize weights
  74844. for (var i = 0; i < weights.length; i++) {
  74845. weights[i] /= totalWeight;
  74846. }
  74847. // Optimize: combine samples to take advantage of hardware linear sampling
  74848. // Walk from left to center, combining pairs (symmetrically)
  74849. var linearSamplingWeights = [];
  74850. var linearSamplingOffsets = [];
  74851. var linearSamplingMap = [];
  74852. for (var i = 0; i <= centerIndex; i += 2) {
  74853. var j = Math.min(i + 1, Math.floor(centerIndex));
  74854. var singleCenterSample = i === j;
  74855. if (singleCenterSample) {
  74856. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74857. }
  74858. else {
  74859. var sharedCell = j === centerIndex;
  74860. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74861. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74862. if (offsetLinear === 0) {
  74863. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74864. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74865. }
  74866. else {
  74867. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74868. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74869. }
  74870. }
  74871. }
  74872. for (var i = 0; i < linearSamplingMap.length; i++) {
  74873. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74874. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74875. }
  74876. // Replace with optimized
  74877. offsets = linearSamplingOffsets;
  74878. weights = linearSamplingWeights;
  74879. // Generate shaders
  74880. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74881. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74882. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74883. var defines = "";
  74884. defines += this._staticDefines;
  74885. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74886. if (this._staticDefines.indexOf("DOF") != -1) {
  74887. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74888. varyingCount--;
  74889. }
  74890. for (var i = 0; i < varyingCount; i++) {
  74891. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74892. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74893. }
  74894. var depCount = 0;
  74895. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74896. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74897. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74898. depCount++;
  74899. }
  74900. if (this.packedFloat) {
  74901. defines += "#define PACKEDFLOAT 1";
  74902. }
  74903. this.blockCompilation = false;
  74904. _super.prototype.updateEffect.call(this, defines, null, null, {
  74905. varyingCount: varyingCount,
  74906. depCount: depCount
  74907. }, onCompiled, onError);
  74908. };
  74909. /**
  74910. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74911. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74912. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74913. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74914. * The gaps between physical kernels are compensated for in the weighting of the samples
  74915. * @param idealKernel Ideal blur kernel.
  74916. * @return Nearest best kernel.
  74917. */
  74918. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74919. var v = Math.round(idealKernel);
  74920. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74921. var k = _a[_i];
  74922. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74923. return Math.max(k, 3);
  74924. }
  74925. }
  74926. return Math.max(v, 3);
  74927. };
  74928. /**
  74929. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74930. * @param x The point on the Gaussian distribution to sample.
  74931. * @return the value of the Gaussian function at x.
  74932. */
  74933. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74934. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74935. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74936. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74937. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74938. // truncated at around 1.3% of peak strength.
  74939. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74940. var sigma = (1 / 3);
  74941. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74942. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74943. var weight = (1.0 / denominator) * Math.exp(exponent);
  74944. return weight;
  74945. };
  74946. /**
  74947. * Generates a string that can be used as a floating point number in GLSL.
  74948. * @param x Value to print.
  74949. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74950. * @return GLSL float string.
  74951. */
  74952. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74953. if (decimalFigures === void 0) { decimalFigures = 8; }
  74954. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74955. };
  74956. return BlurPostProcess;
  74957. }(BABYLON.PostProcess));
  74958. BABYLON.BlurPostProcess = BlurPostProcess;
  74959. })(BABYLON || (BABYLON = {}));
  74960. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74961. var BABYLON;
  74962. (function (BABYLON) {
  74963. /**
  74964. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74965. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74966. * based on samples that have a large difference in distance than the center pixel.
  74967. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74968. */
  74969. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74970. __extends(DepthOfFieldBlurPostProcess, _super);
  74971. /**
  74972. * Creates a new instance CircleOfConfusionPostProcess
  74973. * @param name The name of the effect.
  74974. * @param scene The scene the effect belongs to.
  74975. * @param direction The direction the blur should be applied.
  74976. * @param kernel The size of the kernel used to blur.
  74977. * @param options The required width/height ratio to downsize to before computing the render pass.
  74978. * @param camera The camera to apply the render pass to.
  74979. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74980. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74981. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74982. * @param engine The engine which the post process will be applied. (default: current engine)
  74983. * @param reusable If the post process can be reused on the same frame. (default: false)
  74984. * @param textureType Type of textures used when performing the post process. (default: 0)
  74985. * @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)
  74986. */
  74987. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74988. if (imageToBlur === void 0) { imageToBlur = null; }
  74989. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74990. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74991. if (blockCompilation === void 0) { blockCompilation = false; }
  74992. 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;
  74993. _this.direction = direction;
  74994. _this.onApplyObservable.add(function (effect) {
  74995. if (imageToBlur != null) {
  74996. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74997. }
  74998. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74999. if (scene.activeCamera) {
  75000. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75001. }
  75002. });
  75003. return _this;
  75004. }
  75005. return DepthOfFieldBlurPostProcess;
  75006. }(BABYLON.BlurPostProcess));
  75007. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75008. })(BABYLON || (BABYLON = {}));
  75009. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75010. var BABYLON;
  75011. (function (BABYLON) {
  75012. /**
  75013. * Options to be set when merging outputs from the default pipeline.
  75014. */
  75015. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75016. function DepthOfFieldMergePostProcessOptions() {
  75017. }
  75018. return DepthOfFieldMergePostProcessOptions;
  75019. }());
  75020. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75021. /**
  75022. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75023. */
  75024. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75025. __extends(DepthOfFieldMergePostProcess, _super);
  75026. /**
  75027. * Creates a new instance of DepthOfFieldMergePostProcess
  75028. * @param name The name of the effect.
  75029. * @param originalFromInput Post process which's input will be used for the merge.
  75030. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75031. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75032. * @param options The required width/height ratio to downsize to before computing the render pass.
  75033. * @param camera The camera to apply the render pass to.
  75034. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75035. * @param engine The engine which the post process will be applied. (default: current engine)
  75036. * @param reusable If the post process can be reused on the same frame. (default: false)
  75037. * @param textureType Type of textures used when performing the post process. (default: 0)
  75038. * @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)
  75039. */
  75040. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75041. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75042. if (blockCompilation === void 0) { blockCompilation = false; }
  75043. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75044. _this.blurSteps = blurSteps;
  75045. _this.onApplyObservable.add(function (effect) {
  75046. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75047. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75048. blurSteps.forEach(function (step, index) {
  75049. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75050. });
  75051. });
  75052. if (!blockCompilation) {
  75053. _this.updateEffect();
  75054. }
  75055. return _this;
  75056. }
  75057. /**
  75058. * Updates the effect with the current post process compile time values and recompiles the shader.
  75059. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75060. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75061. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75062. * @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
  75063. * @param onCompiled Called when the shader has been compiled.
  75064. * @param onError Called if there is an error when compiling a shader.
  75065. */
  75066. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75067. if (defines === void 0) { defines = null; }
  75068. if (uniforms === void 0) { uniforms = null; }
  75069. if (samplers === void 0) { samplers = null; }
  75070. if (!defines) {
  75071. defines = "";
  75072. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75073. }
  75074. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75075. };
  75076. return DepthOfFieldMergePostProcess;
  75077. }(BABYLON.PostProcess));
  75078. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75079. })(BABYLON || (BABYLON = {}));
  75080. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75081. var BABYLON;
  75082. (function (BABYLON) {
  75083. /**
  75084. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75085. */
  75086. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75087. __extends(CircleOfConfusionPostProcess, _super);
  75088. /**
  75089. * Creates a new instance CircleOfConfusionPostProcess
  75090. * @param name The name of the effect.
  75091. * @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.
  75092. * @param options The required width/height ratio to downsize to before computing the render pass.
  75093. * @param camera The camera to apply the render pass to.
  75094. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75095. * @param engine The engine which the post process will be applied. (default: current engine)
  75096. * @param reusable If the post process can be reused on the same frame. (default: false)
  75097. * @param textureType Type of textures used when performing the post process. (default: 0)
  75098. * @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)
  75099. */
  75100. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75101. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75102. if (blockCompilation === void 0) { blockCompilation = false; }
  75103. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75104. /**
  75105. * 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.
  75106. */
  75107. _this.lensSize = 50;
  75108. /**
  75109. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75110. */
  75111. _this.fStop = 1.4;
  75112. /**
  75113. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75114. */
  75115. _this.focusDistance = 2000;
  75116. /**
  75117. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75118. */
  75119. _this.focalLength = 50;
  75120. _this._depthTexture = null;
  75121. _this._depthTexture = depthTexture;
  75122. _this.onApplyObservable.add(function (effect) {
  75123. if (!_this._depthTexture) {
  75124. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75125. return;
  75126. }
  75127. effect.setTexture("depthSampler", _this._depthTexture);
  75128. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75129. var aperture = _this.lensSize / _this.fStop;
  75130. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75131. effect.setFloat('focusDistance', _this.focusDistance);
  75132. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75133. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75134. });
  75135. return _this;
  75136. }
  75137. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75138. /**
  75139. * 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.
  75140. */
  75141. set: function (value) {
  75142. this._depthTexture = value;
  75143. },
  75144. enumerable: true,
  75145. configurable: true
  75146. });
  75147. return CircleOfConfusionPostProcess;
  75148. }(BABYLON.PostProcess));
  75149. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75150. })(BABYLON || (BABYLON = {}));
  75151. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75152. var BABYLON;
  75153. (function (BABYLON) {
  75154. /**
  75155. * Specifies the level of max blur that should be applied when using the depth of field effect
  75156. */
  75157. var DepthOfFieldEffectBlurLevel;
  75158. (function (DepthOfFieldEffectBlurLevel) {
  75159. /**
  75160. * Subtle blur
  75161. */
  75162. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75163. /**
  75164. * Medium blur
  75165. */
  75166. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75167. /**
  75168. * Large blur
  75169. */
  75170. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75171. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75172. ;
  75173. /**
  75174. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75175. */
  75176. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75177. __extends(DepthOfFieldEffect, _super);
  75178. /**
  75179. * Creates a new instance DepthOfFieldEffect
  75180. * @param scene The scene the effect belongs to.
  75181. * @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.
  75182. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75183. * @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)
  75184. */
  75185. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75186. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75187. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75188. if (blockCompilation === void 0) { blockCompilation = false; }
  75189. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75190. return _this._effects;
  75191. }, true) || this;
  75192. /**
  75193. * Internal post processes in depth of field effect
  75194. */
  75195. _this._effects = [];
  75196. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75197. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75198. // 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)
  75199. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75200. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75201. _this._depthOfFieldBlurY = [];
  75202. _this._depthOfFieldBlurX = [];
  75203. var blurCount = 1;
  75204. var kernelSize = 15;
  75205. switch (blurLevel) {
  75206. case DepthOfFieldEffectBlurLevel.High: {
  75207. blurCount = 3;
  75208. kernelSize = 51;
  75209. break;
  75210. }
  75211. case DepthOfFieldEffectBlurLevel.Medium: {
  75212. blurCount = 2;
  75213. kernelSize = 31;
  75214. break;
  75215. }
  75216. default: {
  75217. kernelSize = 15;
  75218. blurCount = 1;
  75219. break;
  75220. }
  75221. }
  75222. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75223. var ratio = 1.0;
  75224. for (var i = 0; i < blurCount; i++) {
  75225. 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);
  75226. blurY.autoClear = false;
  75227. ratio = 0.75 / Math.pow(2, i);
  75228. 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);
  75229. blurX.autoClear = false;
  75230. _this._depthOfFieldBlurY.push(blurY);
  75231. _this._depthOfFieldBlurX.push(blurX);
  75232. }
  75233. // Set all post processes on the effect.
  75234. _this._effects = [_this._circleOfConfusion];
  75235. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75236. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75237. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75238. }
  75239. // Merge blurred images with original image based on circleOfConfusion
  75240. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75241. _this._dofMerge.autoClear = false;
  75242. _this._effects.push(_this._dofMerge);
  75243. return _this;
  75244. }
  75245. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75246. get: function () {
  75247. return this._circleOfConfusion.focalLength;
  75248. },
  75249. /**
  75250. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75251. */
  75252. set: function (value) {
  75253. this._circleOfConfusion.focalLength = value;
  75254. },
  75255. enumerable: true,
  75256. configurable: true
  75257. });
  75258. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75259. get: function () {
  75260. return this._circleOfConfusion.fStop;
  75261. },
  75262. /**
  75263. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75264. */
  75265. set: function (value) {
  75266. this._circleOfConfusion.fStop = value;
  75267. },
  75268. enumerable: true,
  75269. configurable: true
  75270. });
  75271. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75272. get: function () {
  75273. return this._circleOfConfusion.focusDistance;
  75274. },
  75275. /**
  75276. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75277. */
  75278. set: function (value) {
  75279. this._circleOfConfusion.focusDistance = value;
  75280. },
  75281. enumerable: true,
  75282. configurable: true
  75283. });
  75284. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75285. get: function () {
  75286. return this._circleOfConfusion.lensSize;
  75287. },
  75288. /**
  75289. * 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.
  75290. */
  75291. set: function (value) {
  75292. this._circleOfConfusion.lensSize = value;
  75293. },
  75294. enumerable: true,
  75295. configurable: true
  75296. });
  75297. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75298. /**
  75299. * 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.
  75300. */
  75301. set: function (value) {
  75302. this._circleOfConfusion.depthTexture = value;
  75303. },
  75304. enumerable: true,
  75305. configurable: true
  75306. });
  75307. /**
  75308. * Disposes each of the internal effects for a given camera.
  75309. * @param camera The camera to dispose the effect on.
  75310. */
  75311. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75312. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75313. this._effects[effectIndex].dispose(camera);
  75314. }
  75315. };
  75316. /**
  75317. * Internal
  75318. */
  75319. DepthOfFieldEffect.prototype._updateEffects = function () {
  75320. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75321. this._effects[effectIndex].updateEffect();
  75322. }
  75323. };
  75324. /**
  75325. * Internal
  75326. * @returns if all the contained post processes are ready.
  75327. */
  75328. DepthOfFieldEffect.prototype._isReady = function () {
  75329. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75330. if (!this._effects[effectIndex].isReady()) {
  75331. return false;
  75332. }
  75333. }
  75334. return true;
  75335. };
  75336. return DepthOfFieldEffect;
  75337. }(BABYLON.PostProcessRenderEffect));
  75338. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75339. })(BABYLON || (BABYLON = {}));
  75340. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75341. var BABYLON;
  75342. (function (BABYLON) {
  75343. /**
  75344. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75345. */
  75346. var BloomMergePostProcess = /** @class */ (function (_super) {
  75347. __extends(BloomMergePostProcess, _super);
  75348. /**
  75349. * Creates a new instance of @see BloomMergePostProcess
  75350. * @param name The name of the effect.
  75351. * @param originalFromInput Post process which's input will be used for the merge.
  75352. * @param blurred Blurred highlights post process which's output will be used.
  75353. * @param weight Weight of the bloom to be added to the original input.
  75354. * @param options The required width/height ratio to downsize to before computing the render pass.
  75355. * @param camera The camera to apply the render pass to.
  75356. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75357. * @param engine The engine which the post process will be applied. (default: current engine)
  75358. * @param reusable If the post process can be reused on the same frame. (default: false)
  75359. * @param textureType Type of textures used when performing the post process. (default: 0)
  75360. * @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)
  75361. */
  75362. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75363. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75364. if (blockCompilation === void 0) { blockCompilation = false; }
  75365. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75366. _this.weight = weight;
  75367. _this.onApplyObservable.add(function (effect) {
  75368. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75369. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75370. effect.setFloat("bloomWeight", _this.weight);
  75371. });
  75372. if (!blockCompilation) {
  75373. _this.updateEffect();
  75374. }
  75375. return _this;
  75376. }
  75377. return BloomMergePostProcess;
  75378. }(BABYLON.PostProcess));
  75379. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75380. })(BABYLON || (BABYLON = {}));
  75381. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75382. var BABYLON;
  75383. (function (BABYLON) {
  75384. /**
  75385. * 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.
  75386. */
  75387. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75388. __extends(ExtractHighlightsPostProcess, _super);
  75389. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75390. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75391. if (blockCompilation === void 0) { blockCompilation = false; }
  75392. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75393. /**
  75394. * The luminance threshold, pixels below this value will be set to black.
  75395. */
  75396. _this.threshold = 0.9;
  75397. /**
  75398. * Internal
  75399. */
  75400. _this._exposure = 1;
  75401. /**
  75402. * Post process which has the input texture to be used when performing highlight extraction
  75403. */
  75404. _this._inputPostProcess = null;
  75405. _this.onApplyObservable.add(function (effect) {
  75406. if (_this._inputPostProcess) {
  75407. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75408. }
  75409. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75410. effect.setFloat('exposure', _this._exposure);
  75411. });
  75412. return _this;
  75413. }
  75414. return ExtractHighlightsPostProcess;
  75415. }(BABYLON.PostProcess));
  75416. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75417. })(BABYLON || (BABYLON = {}));
  75418. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75419. var BABYLON;
  75420. (function (BABYLON) {
  75421. /**
  75422. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75423. */
  75424. var BloomEffect = /** @class */ (function (_super) {
  75425. __extends(BloomEffect, _super);
  75426. /**
  75427. * Creates a new instance of @see BloomEffect
  75428. * @param scene The scene the effect belongs to.
  75429. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75430. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75431. * @param bloomWeight The the strength of bloom.
  75432. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75433. * @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)
  75434. */
  75435. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75436. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75437. if (blockCompilation === void 0) { blockCompilation = false; }
  75438. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75439. return _this._effects;
  75440. }, true) || this;
  75441. _this.bloomScale = bloomScale;
  75442. /**
  75443. * Internal
  75444. */
  75445. _this._effects = [];
  75446. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75447. _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);
  75448. _this._blurX.alwaysForcePOT = true;
  75449. _this._blurX.autoClear = false;
  75450. _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);
  75451. _this._blurY.alwaysForcePOT = true;
  75452. _this._blurY.autoClear = false;
  75453. _this.kernel = bloomKernel;
  75454. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75455. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75456. _this._merge.autoClear = false;
  75457. _this._effects.push(_this._merge);
  75458. return _this;
  75459. }
  75460. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75461. /**
  75462. * The luminance threshold to find bright areas of the image to bloom.
  75463. */
  75464. get: function () {
  75465. return this._downscale.threshold;
  75466. },
  75467. set: function (value) {
  75468. this._downscale.threshold = value;
  75469. },
  75470. enumerable: true,
  75471. configurable: true
  75472. });
  75473. Object.defineProperty(BloomEffect.prototype, "weight", {
  75474. /**
  75475. * The strength of the bloom.
  75476. */
  75477. get: function () {
  75478. return this._merge.weight;
  75479. },
  75480. set: function (value) {
  75481. this._merge.weight = value;
  75482. },
  75483. enumerable: true,
  75484. configurable: true
  75485. });
  75486. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75487. /**
  75488. * Specifies the size of the bloom blur kernel, relative to the final output size
  75489. */
  75490. get: function () {
  75491. return this._blurX.kernel / this.bloomScale;
  75492. },
  75493. set: function (value) {
  75494. this._blurX.kernel = value * this.bloomScale;
  75495. this._blurY.kernel = value * this.bloomScale;
  75496. },
  75497. enumerable: true,
  75498. configurable: true
  75499. });
  75500. /**
  75501. * Disposes each of the internal effects for a given camera.
  75502. * @param camera The camera to dispose the effect on.
  75503. */
  75504. BloomEffect.prototype.disposeEffects = function (camera) {
  75505. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75506. this._effects[effectIndex].dispose(camera);
  75507. }
  75508. };
  75509. /**
  75510. * Internal
  75511. */
  75512. BloomEffect.prototype._updateEffects = function () {
  75513. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75514. this._effects[effectIndex].updateEffect();
  75515. }
  75516. };
  75517. /**
  75518. * Internal
  75519. * @returns if all the contained post processes are ready.
  75520. */
  75521. BloomEffect.prototype._isReady = function () {
  75522. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75523. if (!this._effects[effectIndex].isReady()) {
  75524. return false;
  75525. }
  75526. }
  75527. return true;
  75528. };
  75529. return BloomEffect;
  75530. }(BABYLON.PostProcessRenderEffect));
  75531. BABYLON.BloomEffect = BloomEffect;
  75532. })(BABYLON || (BABYLON = {}));
  75533. //# sourceMappingURL=babylon.bloomEffect.js.map
  75534. var BABYLON;
  75535. (function (BABYLON) {
  75536. /**
  75537. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75538. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75539. */
  75540. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75541. __extends(DefaultRenderingPipeline, _super);
  75542. /**
  75543. * @constructor
  75544. * @param {string} name - The rendering pipeline name
  75545. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75546. * @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)
  75547. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75548. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  75549. */
  75550. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75551. if (automaticBuild === void 0) { automaticBuild = true; }
  75552. var _this = _super.call(this, scene.getEngine(), name) || this;
  75553. _this._originalCameras = [];
  75554. /**
  75555. * ID of the sharpen post process,
  75556. */
  75557. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75558. /**
  75559. * ID of the image processing post process;
  75560. */
  75561. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75562. /**
  75563. * ID of the Fast Approximate Anti-Aliasing post process;
  75564. */
  75565. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75566. /**
  75567. * ID of the chromatic aberration post process,
  75568. */
  75569. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75570. /**
  75571. * ID of the grain post process
  75572. */
  75573. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75574. /**
  75575. * Animations which can be used to tweak settings over a period of time
  75576. */
  75577. _this.animations = [];
  75578. _this._imageProcessingConfigurationObserver = null;
  75579. // Values
  75580. _this._sharpenEnabled = false;
  75581. _this._bloomEnabled = false;
  75582. _this._depthOfFieldEnabled = false;
  75583. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75584. _this._fxaaEnabled = false;
  75585. _this._imageProcessingEnabled = true;
  75586. _this._bloomScale = 0.5;
  75587. _this._chromaticAberrationEnabled = false;
  75588. _this._grainEnabled = false;
  75589. _this._buildAllowed = true;
  75590. _this._resizeObserver = null;
  75591. _this._hardwareScaleLevel = 1.0;
  75592. _this._bloomKernel = 64;
  75593. /**
  75594. * Specifies the weight of the bloom in the final rendering
  75595. */
  75596. _this._bloomWeight = 0.15;
  75597. /**
  75598. * Specifies the luma threshold for the area that will be blurred by the bloom
  75599. */
  75600. _this._bloomThreshold = 0.9;
  75601. _this._samples = 1;
  75602. _this._hasCleared = false;
  75603. _this._prevPostProcess = null;
  75604. _this._prevPrevPostProcess = null;
  75605. _this._cameras = cameras || [];
  75606. _this._originalCameras = _this._cameras.slice();
  75607. _this._buildAllowed = automaticBuild;
  75608. // Initialize
  75609. _this._scene = scene;
  75610. var caps = _this._scene.getEngine().getCaps();
  75611. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75612. // Misc
  75613. if (_this._hdr) {
  75614. if (caps.textureHalfFloatRender) {
  75615. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75616. }
  75617. else if (caps.textureFloatRender) {
  75618. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75619. }
  75620. }
  75621. else {
  75622. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75623. }
  75624. // Attach
  75625. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75626. var engine = _this._scene.getEngine();
  75627. // Create post processes before hand so they can be modified before enabled.
  75628. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75629. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75630. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75631. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75632. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75633. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75634. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75635. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75636. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75637. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75638. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75639. _this.bloomKernel = _this.bloomKernel;
  75640. });
  75641. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75642. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75643. });
  75644. _this._buildPipeline();
  75645. return _this;
  75646. }
  75647. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75648. get: function () {
  75649. return this._sharpenEnabled;
  75650. },
  75651. /**
  75652. * Enable or disable the sharpen process from the pipeline
  75653. */
  75654. set: function (enabled) {
  75655. if (this._sharpenEnabled === enabled) {
  75656. return;
  75657. }
  75658. this._sharpenEnabled = enabled;
  75659. this._buildPipeline();
  75660. },
  75661. enumerable: true,
  75662. configurable: true
  75663. });
  75664. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75665. /**
  75666. * Specifies the size of the bloom blur kernel, relative to the final output size
  75667. */
  75668. get: function () {
  75669. return this._bloomKernel;
  75670. },
  75671. set: function (value) {
  75672. this._bloomKernel = value;
  75673. this.bloom.kernel = value / this._hardwareScaleLevel;
  75674. },
  75675. enumerable: true,
  75676. configurable: true
  75677. });
  75678. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75679. get: function () {
  75680. return this._bloomWeight;
  75681. },
  75682. /**
  75683. * The strength of the bloom.
  75684. */
  75685. set: function (value) {
  75686. if (this._bloomWeight === value) {
  75687. return;
  75688. }
  75689. this.bloom.weight = value;
  75690. this._bloomWeight = value;
  75691. },
  75692. enumerable: true,
  75693. configurable: true
  75694. });
  75695. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75696. get: function () {
  75697. return this._bloomThreshold;
  75698. },
  75699. /**
  75700. * The strength of the bloom.
  75701. */
  75702. set: function (value) {
  75703. if (this._bloomThreshold === value) {
  75704. return;
  75705. }
  75706. this.bloom.threshold = value;
  75707. this._bloomThreshold = value;
  75708. },
  75709. enumerable: true,
  75710. configurable: true
  75711. });
  75712. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75713. get: function () {
  75714. return this._bloomScale;
  75715. },
  75716. /**
  75717. * The scale of the bloom, lower value will provide better performance.
  75718. */
  75719. set: function (value) {
  75720. if (this._bloomScale === value) {
  75721. return;
  75722. }
  75723. this._bloomScale = value;
  75724. // recreate bloom and dispose old as this setting is not dynamic
  75725. this._rebuildBloom();
  75726. this._buildPipeline();
  75727. },
  75728. enumerable: true,
  75729. configurable: true
  75730. });
  75731. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75732. get: function () {
  75733. return this._bloomEnabled;
  75734. },
  75735. /**
  75736. * Enable or disable the bloom from the pipeline
  75737. */
  75738. set: function (enabled) {
  75739. if (this._bloomEnabled === enabled) {
  75740. return;
  75741. }
  75742. this._bloomEnabled = enabled;
  75743. this._buildPipeline();
  75744. },
  75745. enumerable: true,
  75746. configurable: true
  75747. });
  75748. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75749. // recreate bloom and dispose old as this setting is not dynamic
  75750. var oldBloom = this.bloom;
  75751. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75752. this.bloom.threshold = oldBloom.threshold;
  75753. for (var i = 0; i < this._cameras.length; i++) {
  75754. oldBloom.disposeEffects(this._cameras[i]);
  75755. }
  75756. };
  75757. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75758. /**
  75759. * If the depth of field is enabled.
  75760. */
  75761. get: function () {
  75762. return this._depthOfFieldEnabled;
  75763. },
  75764. set: function (enabled) {
  75765. if (this._depthOfFieldEnabled === enabled) {
  75766. return;
  75767. }
  75768. this._depthOfFieldEnabled = enabled;
  75769. this._buildPipeline();
  75770. },
  75771. enumerable: true,
  75772. configurable: true
  75773. });
  75774. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75775. /**
  75776. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75777. */
  75778. get: function () {
  75779. return this._depthOfFieldBlurLevel;
  75780. },
  75781. set: function (value) {
  75782. if (this._depthOfFieldBlurLevel === value) {
  75783. return;
  75784. }
  75785. this._depthOfFieldBlurLevel = value;
  75786. // recreate dof and dispose old as this setting is not dynamic
  75787. var oldDof = this.depthOfField;
  75788. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75789. this.depthOfField.focalLength = oldDof.focalLength;
  75790. this.depthOfField.focusDistance = oldDof.focusDistance;
  75791. this.depthOfField.fStop = oldDof.fStop;
  75792. this.depthOfField.lensSize = oldDof.lensSize;
  75793. for (var i = 0; i < this._cameras.length; i++) {
  75794. oldDof.disposeEffects(this._cameras[i]);
  75795. }
  75796. this._buildPipeline();
  75797. },
  75798. enumerable: true,
  75799. configurable: true
  75800. });
  75801. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75802. get: function () {
  75803. return this._fxaaEnabled;
  75804. },
  75805. /**
  75806. * If the anti aliasing is enabled.
  75807. */
  75808. set: function (enabled) {
  75809. if (this._fxaaEnabled === enabled) {
  75810. return;
  75811. }
  75812. this._fxaaEnabled = enabled;
  75813. this._buildPipeline();
  75814. },
  75815. enumerable: true,
  75816. configurable: true
  75817. });
  75818. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75819. get: function () {
  75820. return this._samples;
  75821. },
  75822. /**
  75823. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75824. */
  75825. set: function (sampleCount) {
  75826. if (this._samples === sampleCount) {
  75827. return;
  75828. }
  75829. this._samples = sampleCount;
  75830. this._buildPipeline();
  75831. },
  75832. enumerable: true,
  75833. configurable: true
  75834. });
  75835. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75836. get: function () {
  75837. return this._imageProcessingEnabled;
  75838. },
  75839. /**
  75840. * If image processing is enabled.
  75841. */
  75842. set: function (enabled) {
  75843. if (this._imageProcessingEnabled === enabled) {
  75844. return;
  75845. }
  75846. this._imageProcessingEnabled = enabled;
  75847. this._buildPipeline();
  75848. },
  75849. enumerable: true,
  75850. configurable: true
  75851. });
  75852. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75853. get: function () {
  75854. return this._chromaticAberrationEnabled;
  75855. },
  75856. /**
  75857. * Enable or disable the chromaticAberration process from the pipeline
  75858. */
  75859. set: function (enabled) {
  75860. if (this._chromaticAberrationEnabled === enabled) {
  75861. return;
  75862. }
  75863. this._chromaticAberrationEnabled = enabled;
  75864. this._buildPipeline();
  75865. },
  75866. enumerable: true,
  75867. configurable: true
  75868. });
  75869. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75870. get: function () {
  75871. return this._grainEnabled;
  75872. },
  75873. /**
  75874. * Enable or disable the grain process from the pipeline
  75875. */
  75876. set: function (enabled) {
  75877. if (this._grainEnabled === enabled) {
  75878. return;
  75879. }
  75880. this._grainEnabled = enabled;
  75881. this._buildPipeline();
  75882. },
  75883. enumerable: true,
  75884. configurable: true
  75885. });
  75886. /**
  75887. * Force the compilation of the entire pipeline.
  75888. */
  75889. DefaultRenderingPipeline.prototype.prepare = function () {
  75890. var previousState = this._buildAllowed;
  75891. this._buildAllowed = true;
  75892. this._buildPipeline();
  75893. this._buildAllowed = previousState;
  75894. };
  75895. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75896. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75897. if (this._hasCleared) {
  75898. postProcess.autoClear = false;
  75899. }
  75900. else {
  75901. postProcess.autoClear = true;
  75902. this._scene.autoClear = false;
  75903. this._hasCleared = true;
  75904. }
  75905. if (!skipTextureSharing) {
  75906. if (this._prevPrevPostProcess) {
  75907. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75908. }
  75909. else {
  75910. postProcess.useOwnOutput();
  75911. }
  75912. if (this._prevPostProcess) {
  75913. this._prevPrevPostProcess = this._prevPostProcess;
  75914. }
  75915. this._prevPostProcess = postProcess;
  75916. }
  75917. };
  75918. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75919. var _this = this;
  75920. if (!this._buildAllowed) {
  75921. return;
  75922. }
  75923. this._scene.autoClear = true;
  75924. var engine = this._scene.getEngine();
  75925. this._disposePostProcesses();
  75926. if (this._cameras !== null) {
  75927. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75928. // get back cameras to be used to reattach pipeline
  75929. this._cameras = this._originalCameras.slice();
  75930. }
  75931. this._reset();
  75932. this._prevPostProcess = null;
  75933. this._prevPrevPostProcess = null;
  75934. this._hasCleared = false;
  75935. if (this.depthOfFieldEnabled) {
  75936. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75937. this.depthOfField.depthTexture = depthTexture;
  75938. if (!this.depthOfField._isReady()) {
  75939. this.depthOfField._updateEffects();
  75940. }
  75941. this.addEffect(this.depthOfField);
  75942. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75943. }
  75944. if (this.bloomEnabled) {
  75945. if (!this.bloom._isReady()) {
  75946. this.bloom._updateEffects();
  75947. }
  75948. this.addEffect(this.bloom);
  75949. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75950. }
  75951. if (this._imageProcessingEnabled) {
  75952. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75953. if (this._hdr) {
  75954. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75955. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75956. }
  75957. else {
  75958. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75959. }
  75960. }
  75961. if (this.sharpenEnabled) {
  75962. if (!this.sharpen.isReady()) {
  75963. this.sharpen.updateEffect();
  75964. }
  75965. this.addEffect(this._sharpenEffect);
  75966. this._setAutoClearAndTextureSharing(this.sharpen);
  75967. }
  75968. if (this.grainEnabled) {
  75969. if (!this.grain.isReady()) {
  75970. this.grain.updateEffect();
  75971. }
  75972. this.addEffect(this._grainEffect);
  75973. this._setAutoClearAndTextureSharing(this.grain);
  75974. }
  75975. if (this.chromaticAberrationEnabled) {
  75976. if (!this.chromaticAberration.isReady()) {
  75977. this.chromaticAberration.updateEffect();
  75978. }
  75979. this.addEffect(this._chromaticAberrationEffect);
  75980. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75981. }
  75982. if (this.fxaaEnabled) {
  75983. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75984. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75985. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75986. }
  75987. if (this._cameras !== null) {
  75988. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75989. }
  75990. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75991. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75992. }
  75993. };
  75994. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75995. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75996. for (var i = 0; i < this._cameras.length; i++) {
  75997. var camera = this._cameras[i];
  75998. if (this.imageProcessing) {
  75999. this.imageProcessing.dispose(camera);
  76000. }
  76001. if (this.fxaa) {
  76002. this.fxaa.dispose(camera);
  76003. }
  76004. // These are created in the constructor and should not be disposed on every pipeline change
  76005. if (disposeNonRecreated) {
  76006. if (this.sharpen) {
  76007. this.sharpen.dispose(camera);
  76008. }
  76009. if (this.depthOfField) {
  76010. this.depthOfField.disposeEffects(camera);
  76011. }
  76012. if (this.bloom) {
  76013. this.bloom.disposeEffects(camera);
  76014. }
  76015. if (this.chromaticAberration) {
  76016. this.chromaticAberration.dispose(camera);
  76017. }
  76018. if (this.grain) {
  76019. this.grain.dispose(camera);
  76020. }
  76021. }
  76022. }
  76023. this.imageProcessing = null;
  76024. this.fxaa = null;
  76025. if (disposeNonRecreated) {
  76026. this.sharpen = null;
  76027. this._sharpenEffect = null;
  76028. this.depthOfField = null;
  76029. this.bloom = null;
  76030. this.chromaticAberration = null;
  76031. this._chromaticAberrationEffect = null;
  76032. this.grain = null;
  76033. this._grainEffect = null;
  76034. }
  76035. };
  76036. /**
  76037. * Dispose of the pipeline and stop all post processes
  76038. */
  76039. DefaultRenderingPipeline.prototype.dispose = function () {
  76040. this._disposePostProcesses(true);
  76041. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76042. this._scene.autoClear = true;
  76043. if (this._resizeObserver) {
  76044. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76045. this._resizeObserver = null;
  76046. }
  76047. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76048. _super.prototype.dispose.call(this);
  76049. };
  76050. /**
  76051. * Serialize the rendering pipeline (Used when exporting)
  76052. * @returns the serialized object
  76053. */
  76054. DefaultRenderingPipeline.prototype.serialize = function () {
  76055. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76056. serializationObject.customType = "DefaultRenderingPipeline";
  76057. return serializationObject;
  76058. };
  76059. /**
  76060. * Parse the serialized pipeline
  76061. * @param source Source pipeline.
  76062. * @param scene The scene to load the pipeline to.
  76063. * @param rootUrl The URL of the serialized pipeline.
  76064. * @returns An instantiated pipeline from the serialized object.
  76065. */
  76066. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76067. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76068. };
  76069. __decorate([
  76070. BABYLON.serialize()
  76071. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76072. __decorate([
  76073. BABYLON.serialize()
  76074. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76075. __decorate([
  76076. BABYLON.serialize()
  76077. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76078. __decorate([
  76079. BABYLON.serialize()
  76080. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76081. __decorate([
  76082. BABYLON.serialize()
  76083. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76084. __decorate([
  76085. BABYLON.serialize()
  76086. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76087. __decorate([
  76088. BABYLON.serialize()
  76089. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76090. __decorate([
  76091. BABYLON.serialize()
  76092. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76093. __decorate([
  76094. BABYLON.serialize()
  76095. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76096. __decorate([
  76097. BABYLON.serialize()
  76098. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76099. __decorate([
  76100. BABYLON.serialize()
  76101. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76102. __decorate([
  76103. BABYLON.serialize()
  76104. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76105. __decorate([
  76106. BABYLON.serialize()
  76107. ], DefaultRenderingPipeline.prototype, "samples", null);
  76108. __decorate([
  76109. BABYLON.serialize()
  76110. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76111. __decorate([
  76112. BABYLON.serialize()
  76113. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76114. __decorate([
  76115. BABYLON.serialize()
  76116. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76117. return DefaultRenderingPipeline;
  76118. }(BABYLON.PostProcessRenderPipeline));
  76119. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76120. })(BABYLON || (BABYLON = {}));
  76121. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76122. var BABYLON;
  76123. (function (BABYLON) {
  76124. /**
  76125. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76126. */
  76127. var GeometryBufferRenderer = /** @class */ (function () {
  76128. /**
  76129. * Creates a new G Buffer for the scene
  76130. * @param scene The scene the buffer belongs to
  76131. * @param ratio How big is the buffer related to the main canvas.
  76132. */
  76133. function GeometryBufferRenderer(scene, ratio) {
  76134. if (ratio === void 0) { ratio = 1; }
  76135. this._enablePosition = false;
  76136. this._scene = scene;
  76137. this._ratio = ratio;
  76138. // Render target
  76139. this._createRenderTargets();
  76140. }
  76141. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76142. /**
  76143. * Set the render list (meshes to be rendered) used in the G buffer.
  76144. */
  76145. set: function (meshes) {
  76146. this._multiRenderTarget.renderList = meshes;
  76147. },
  76148. enumerable: true,
  76149. configurable: true
  76150. });
  76151. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76152. /**
  76153. * Gets wether or not G buffer are supported by the running hardware.
  76154. * This requires draw buffer supports
  76155. */
  76156. get: function () {
  76157. return this._multiRenderTarget.isSupported;
  76158. },
  76159. enumerable: true,
  76160. configurable: true
  76161. });
  76162. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76163. /**
  76164. * Gets wether or not position are enabled for the G buffer.
  76165. */
  76166. get: function () {
  76167. return this._enablePosition;
  76168. },
  76169. /**
  76170. * Sets wether or not position are enabled for the G buffer.
  76171. */
  76172. set: function (enable) {
  76173. this._enablePosition = enable;
  76174. this.dispose();
  76175. this._createRenderTargets();
  76176. },
  76177. enumerable: true,
  76178. configurable: true
  76179. });
  76180. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76181. /**
  76182. * Gets the scene associated with the buffer.
  76183. */
  76184. get: function () {
  76185. return this._scene;
  76186. },
  76187. enumerable: true,
  76188. configurable: true
  76189. });
  76190. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76191. /**
  76192. * Gets the ratio used by the buffer during its creation.
  76193. * How big is the buffer related to the main canvas.
  76194. */
  76195. get: function () {
  76196. return this._ratio;
  76197. },
  76198. enumerable: true,
  76199. configurable: true
  76200. });
  76201. /**
  76202. * Checks wether everything is ready to render a submesh to the G buffer.
  76203. * @param subMesh the submesh to check readiness for
  76204. * @param useInstances is the mesh drawn using instance or not
  76205. * @returns true if ready otherwise false
  76206. */
  76207. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76208. var material = subMesh.getMaterial();
  76209. if (material && material.disableDepthWrite) {
  76210. return false;
  76211. }
  76212. var defines = [];
  76213. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76214. var mesh = subMesh.getMesh();
  76215. // Alpha test
  76216. if (material && material.needAlphaTesting()) {
  76217. defines.push("#define ALPHATEST");
  76218. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76219. attribs.push(BABYLON.VertexBuffer.UVKind);
  76220. defines.push("#define UV1");
  76221. }
  76222. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76223. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76224. defines.push("#define UV2");
  76225. }
  76226. }
  76227. // Buffers
  76228. if (this._enablePosition) {
  76229. defines.push("#define POSITION");
  76230. }
  76231. // Bones
  76232. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76233. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76234. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76235. if (mesh.numBoneInfluencers > 4) {
  76236. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76237. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76238. }
  76239. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76240. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76241. }
  76242. else {
  76243. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76244. }
  76245. // Instances
  76246. if (useInstances) {
  76247. defines.push("#define INSTANCES");
  76248. attribs.push("world0");
  76249. attribs.push("world1");
  76250. attribs.push("world2");
  76251. attribs.push("world3");
  76252. }
  76253. // Get correct effect
  76254. var join = defines.join("\n");
  76255. if (this._cachedDefines !== join) {
  76256. this._cachedDefines = join;
  76257. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76258. }
  76259. return this._effect.isReady();
  76260. };
  76261. /**
  76262. * Gets the current underlying G Buffer.
  76263. * @returns the buffer
  76264. */
  76265. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76266. return this._multiRenderTarget;
  76267. };
  76268. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76269. /**
  76270. * Gets the number of samples used to render the buffer (anti aliasing).
  76271. */
  76272. get: function () {
  76273. return this._multiRenderTarget.samples;
  76274. },
  76275. /**
  76276. * Sets the number of samples used to render the buffer (anti aliasing).
  76277. */
  76278. set: function (value) {
  76279. this._multiRenderTarget.samples = value;
  76280. },
  76281. enumerable: true,
  76282. configurable: true
  76283. });
  76284. /**
  76285. * Disposes the renderer and frees up associated resources.
  76286. */
  76287. GeometryBufferRenderer.prototype.dispose = function () {
  76288. this.getGBuffer().dispose();
  76289. };
  76290. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76291. var _this = this;
  76292. var engine = this._scene.getEngine();
  76293. var count = this._enablePosition ? 3 : 2;
  76294. 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 });
  76295. if (!this.isSupported) {
  76296. return;
  76297. }
  76298. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76299. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76300. this._multiRenderTarget.refreshRate = 1;
  76301. this._multiRenderTarget.renderParticles = false;
  76302. this._multiRenderTarget.renderList = null;
  76303. // set default depth value to 1.0 (far away)
  76304. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76305. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76306. });
  76307. // Custom render function
  76308. var renderSubMesh = function (subMesh) {
  76309. var mesh = subMesh.getRenderingMesh();
  76310. var scene = _this._scene;
  76311. var engine = scene.getEngine();
  76312. var material = subMesh.getMaterial();
  76313. if (!material) {
  76314. return;
  76315. }
  76316. // Culling
  76317. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76318. // Managing instances
  76319. var batch = mesh._getInstancesRenderList(subMesh._id);
  76320. if (batch.mustReturn) {
  76321. return;
  76322. }
  76323. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76324. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76325. engine.enableEffect(_this._effect);
  76326. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76327. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76328. _this._effect.setMatrix("view", scene.getViewMatrix());
  76329. // Alpha test
  76330. if (material && material.needAlphaTesting()) {
  76331. var alphaTexture = material.getAlphaTestTexture();
  76332. if (alphaTexture) {
  76333. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76334. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76335. }
  76336. }
  76337. // Bones
  76338. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76339. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76340. }
  76341. // Draw
  76342. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76343. }
  76344. };
  76345. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76346. var index;
  76347. if (depthOnlySubMeshes.length) {
  76348. engine.setColorWrite(false);
  76349. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76350. renderSubMesh(depthOnlySubMeshes.data[index]);
  76351. }
  76352. engine.setColorWrite(true);
  76353. }
  76354. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76355. renderSubMesh(opaqueSubMeshes.data[index]);
  76356. }
  76357. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76358. renderSubMesh(alphaTestSubMeshes.data[index]);
  76359. }
  76360. };
  76361. };
  76362. return GeometryBufferRenderer;
  76363. }());
  76364. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76365. })(BABYLON || (BABYLON = {}));
  76366. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76367. var BABYLON;
  76368. (function (BABYLON) {
  76369. var RefractionPostProcess = /** @class */ (function (_super) {
  76370. __extends(RefractionPostProcess, _super);
  76371. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76372. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76373. _this.color = color;
  76374. _this.depth = depth;
  76375. _this.colorLevel = colorLevel;
  76376. _this._ownRefractionTexture = true;
  76377. _this.onActivateObservable.add(function (cam) {
  76378. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76379. });
  76380. _this.onApplyObservable.add(function (effect) {
  76381. effect.setColor3("baseColor", _this.color);
  76382. effect.setFloat("depth", _this.depth);
  76383. effect.setFloat("colorLevel", _this.colorLevel);
  76384. effect.setTexture("refractionSampler", _this._refTexture);
  76385. });
  76386. return _this;
  76387. }
  76388. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76389. /**
  76390. * Gets or sets the refraction texture
  76391. * Please note that you are responsible for disposing the texture if you set it manually
  76392. */
  76393. get: function () {
  76394. return this._refTexture;
  76395. },
  76396. set: function (value) {
  76397. if (this._refTexture && this._ownRefractionTexture) {
  76398. this._refTexture.dispose();
  76399. }
  76400. this._refTexture = value;
  76401. this._ownRefractionTexture = false;
  76402. },
  76403. enumerable: true,
  76404. configurable: true
  76405. });
  76406. // Methods
  76407. RefractionPostProcess.prototype.dispose = function (camera) {
  76408. if (this._refTexture && this._ownRefractionTexture) {
  76409. this._refTexture.dispose();
  76410. this._refTexture = null;
  76411. }
  76412. _super.prototype.dispose.call(this, camera);
  76413. };
  76414. return RefractionPostProcess;
  76415. }(BABYLON.PostProcess));
  76416. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76417. })(BABYLON || (BABYLON = {}));
  76418. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76419. var BABYLON;
  76420. (function (BABYLON) {
  76421. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76422. __extends(BlackAndWhitePostProcess, _super);
  76423. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76424. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76425. _this.degree = 1;
  76426. _this.onApplyObservable.add(function (effect) {
  76427. effect.setFloat("degree", _this.degree);
  76428. });
  76429. return _this;
  76430. }
  76431. return BlackAndWhitePostProcess;
  76432. }(BABYLON.PostProcess));
  76433. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76434. })(BABYLON || (BABYLON = {}));
  76435. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76436. var BABYLON;
  76437. (function (BABYLON) {
  76438. /**
  76439. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76440. * input texture to perform effects such as edge detection or sharpening
  76441. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76442. */
  76443. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76444. __extends(ConvolutionPostProcess, _super);
  76445. /**
  76446. * Creates a new instance ConvolutionPostProcess
  76447. * @param name The name of the effect.
  76448. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76449. * @param options The required width/height ratio to downsize to before computing the render pass.
  76450. * @param camera The camera to apply the render pass to.
  76451. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76452. * @param engine The engine which the post process will be applied. (default: current engine)
  76453. * @param reusable If the post process can be reused on the same frame. (default: false)
  76454. * @param textureType Type of textures used when performing the post process. (default: 0)
  76455. */
  76456. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76457. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76458. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76459. _this.kernel = kernel;
  76460. _this.onApply = function (effect) {
  76461. effect.setFloat2("screenSize", _this.width, _this.height);
  76462. effect.setArray("kernel", _this.kernel);
  76463. };
  76464. return _this;
  76465. }
  76466. // Statics
  76467. /**
  76468. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76469. */
  76470. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76471. /**
  76472. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76473. */
  76474. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76475. /**
  76476. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76477. */
  76478. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76479. /**
  76480. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76481. */
  76482. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76483. /**
  76484. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76485. */
  76486. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76487. /**
  76488. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76489. */
  76490. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76491. return ConvolutionPostProcess;
  76492. }(BABYLON.PostProcess));
  76493. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  76494. })(BABYLON || (BABYLON = {}));
  76495. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  76496. var BABYLON;
  76497. (function (BABYLON) {
  76498. var FilterPostProcess = /** @class */ (function (_super) {
  76499. __extends(FilterPostProcess, _super);
  76500. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  76501. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  76502. _this.kernelMatrix = kernelMatrix;
  76503. _this.onApply = function (effect) {
  76504. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  76505. };
  76506. return _this;
  76507. }
  76508. return FilterPostProcess;
  76509. }(BABYLON.PostProcess));
  76510. BABYLON.FilterPostProcess = FilterPostProcess;
  76511. })(BABYLON || (BABYLON = {}));
  76512. //# sourceMappingURL=babylon.filterPostProcess.js.map
  76513. var BABYLON;
  76514. (function (BABYLON) {
  76515. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  76516. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  76517. __extends(VolumetricLightScatteringPostProcess, _super);
  76518. /**
  76519. * @constructor
  76520. * @param {string} name - The post-process name
  76521. * @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)
  76522. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  76523. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  76524. * @param {number} samples - The post-process quality, default 100
  76525. * @param {number} samplingMode - The post-process filtering mode
  76526. * @param {BABYLON.Engine} engine - The babylon engine
  76527. * @param {boolean} reusable - If the post-process is reusable
  76528. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  76529. */
  76530. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  76531. if (samples === void 0) { samples = 100; }
  76532. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76533. 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;
  76534. _this._screenCoordinates = BABYLON.Vector2.Zero();
  76535. /**
  76536. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  76537. */
  76538. _this.customMeshPosition = BABYLON.Vector3.Zero();
  76539. /**
  76540. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  76541. */
  76542. _this.useCustomMeshPosition = false;
  76543. /**
  76544. * If the post-process should inverse the light scattering direction
  76545. */
  76546. _this.invert = true;
  76547. /**
  76548. * Array containing the excluded meshes not rendered in the internal pass
  76549. */
  76550. _this.excludedMeshes = new Array();
  76551. /**
  76552. * Controls the overall intensity of the post-process
  76553. */
  76554. _this.exposure = 0.3;
  76555. /**
  76556. * Dissipates each sample's contribution in range [0, 1]
  76557. */
  76558. _this.decay = 0.96815;
  76559. /**
  76560. * Controls the overall intensity of each sample
  76561. */
  76562. _this.weight = 0.58767;
  76563. /**
  76564. * Controls the density of each sample
  76565. */
  76566. _this.density = 0.926;
  76567. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  76568. engine = scene.getEngine();
  76569. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  76570. // Configure mesh
  76571. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  76572. // Configure
  76573. _this._createPass(scene, ratio.passRatio || ratio);
  76574. _this.onActivate = function (camera) {
  76575. if (!_this.isSupported) {
  76576. _this.dispose(camera);
  76577. }
  76578. _this.onActivate = null;
  76579. };
  76580. _this.onApplyObservable.add(function (effect) {
  76581. _this._updateMeshScreenCoordinates(scene);
  76582. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  76583. effect.setFloat("exposure", _this.exposure);
  76584. effect.setFloat("decay", _this.decay);
  76585. effect.setFloat("weight", _this.weight);
  76586. effect.setFloat("density", _this.density);
  76587. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  76588. });
  76589. return _this;
  76590. }
  76591. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  76592. get: function () {
  76593. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76594. return false;
  76595. },
  76596. set: function (useDiffuseColor) {
  76597. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76598. },
  76599. enumerable: true,
  76600. configurable: true
  76601. });
  76602. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  76603. return "VolumetricLightScatteringPostProcess";
  76604. };
  76605. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  76606. var mesh = subMesh.getMesh();
  76607. // Render this.mesh as default
  76608. if (mesh === this.mesh && mesh.material) {
  76609. return mesh.material.isReady(mesh);
  76610. }
  76611. var defines = [];
  76612. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76613. var material = subMesh.getMaterial();
  76614. // Alpha test
  76615. if (material) {
  76616. if (material.needAlphaTesting()) {
  76617. defines.push("#define ALPHATEST");
  76618. }
  76619. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76620. attribs.push(BABYLON.VertexBuffer.UVKind);
  76621. defines.push("#define UV1");
  76622. }
  76623. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76624. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76625. defines.push("#define UV2");
  76626. }
  76627. }
  76628. // Bones
  76629. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76630. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76631. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76632. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76633. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76634. }
  76635. else {
  76636. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76637. }
  76638. // Instances
  76639. if (useInstances) {
  76640. defines.push("#define INSTANCES");
  76641. attribs.push("world0");
  76642. attribs.push("world1");
  76643. attribs.push("world2");
  76644. attribs.push("world3");
  76645. }
  76646. // Get correct effect
  76647. var join = defines.join("\n");
  76648. if (this._cachedDefines !== join) {
  76649. this._cachedDefines = join;
  76650. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  76651. }
  76652. return this._volumetricLightScatteringPass.isReady();
  76653. };
  76654. /**
  76655. * Sets the new light position for light scattering effect
  76656. * @param {BABYLON.Vector3} The new custom light position
  76657. */
  76658. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  76659. this.customMeshPosition = position;
  76660. };
  76661. /**
  76662. * Returns the light position for light scattering effect
  76663. * @return {BABYLON.Vector3} The custom light position
  76664. */
  76665. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  76666. return this.customMeshPosition;
  76667. };
  76668. /**
  76669. * Disposes the internal assets and detaches the post-process from the camera
  76670. */
  76671. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  76672. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  76673. if (rttIndex !== -1) {
  76674. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  76675. }
  76676. this._volumetricLightScatteringRTT.dispose();
  76677. _super.prototype.dispose.call(this, camera);
  76678. };
  76679. /**
  76680. * Returns the render target texture used by the post-process
  76681. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  76682. */
  76683. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  76684. return this._volumetricLightScatteringRTT;
  76685. };
  76686. // Private methods
  76687. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  76688. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  76689. return true;
  76690. }
  76691. return false;
  76692. };
  76693. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  76694. var _this = this;
  76695. var engine = scene.getEngine();
  76696. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76697. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76698. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76699. this._volumetricLightScatteringRTT.renderList = null;
  76700. this._volumetricLightScatteringRTT.renderParticles = false;
  76701. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  76702. var camera = this.getCamera();
  76703. if (camera) {
  76704. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76705. }
  76706. else {
  76707. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76708. }
  76709. // Custom render function for submeshes
  76710. var renderSubMesh = function (subMesh) {
  76711. var mesh = subMesh.getRenderingMesh();
  76712. if (_this._meshExcluded(mesh)) {
  76713. return;
  76714. }
  76715. var material = subMesh.getMaterial();
  76716. if (!material) {
  76717. return;
  76718. }
  76719. var scene = mesh.getScene();
  76720. var engine = scene.getEngine();
  76721. // Culling
  76722. engine.setState(material.backFaceCulling);
  76723. // Managing instances
  76724. var batch = mesh._getInstancesRenderList(subMesh._id);
  76725. if (batch.mustReturn) {
  76726. return;
  76727. }
  76728. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76729. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  76730. var effect = _this._volumetricLightScatteringPass;
  76731. if (mesh === _this.mesh) {
  76732. if (subMesh.effect) {
  76733. effect = subMesh.effect;
  76734. }
  76735. else {
  76736. effect = material.getEffect();
  76737. }
  76738. }
  76739. engine.enableEffect(effect);
  76740. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  76741. if (mesh === _this.mesh) {
  76742. material.bind(mesh.getWorldMatrix(), mesh);
  76743. }
  76744. else {
  76745. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  76746. // Alpha test
  76747. if (material && material.needAlphaTesting()) {
  76748. var alphaTexture = material.getAlphaTestTexture();
  76749. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  76750. if (alphaTexture) {
  76751. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76752. }
  76753. }
  76754. // Bones
  76755. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76756. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76757. }
  76758. }
  76759. // Draw
  76760. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76761. }
  76762. };
  76763. // Render target texture callbacks
  76764. var savedSceneClearColor;
  76765. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76766. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76767. savedSceneClearColor = scene.clearColor;
  76768. scene.clearColor = sceneClearColor;
  76769. });
  76770. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76771. scene.clearColor = savedSceneClearColor;
  76772. });
  76773. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76774. var engine = scene.getEngine();
  76775. var index;
  76776. if (depthOnlySubMeshes.length) {
  76777. engine.setColorWrite(false);
  76778. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76779. renderSubMesh(depthOnlySubMeshes.data[index]);
  76780. }
  76781. engine.setColorWrite(true);
  76782. }
  76783. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76784. renderSubMesh(opaqueSubMeshes.data[index]);
  76785. }
  76786. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76787. renderSubMesh(alphaTestSubMeshes.data[index]);
  76788. }
  76789. if (transparentSubMeshes.length) {
  76790. // Sort sub meshes
  76791. for (index = 0; index < transparentSubMeshes.length; index++) {
  76792. var submesh = transparentSubMeshes.data[index];
  76793. var boundingInfo = submesh.getBoundingInfo();
  76794. if (boundingInfo && scene.activeCamera) {
  76795. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  76796. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  76797. }
  76798. }
  76799. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  76800. sortedArray.sort(function (a, b) {
  76801. // Alpha index first
  76802. if (a._alphaIndex > b._alphaIndex) {
  76803. return 1;
  76804. }
  76805. if (a._alphaIndex < b._alphaIndex) {
  76806. return -1;
  76807. }
  76808. // Then distance to camera
  76809. if (a._distanceToCamera < b._distanceToCamera) {
  76810. return 1;
  76811. }
  76812. if (a._distanceToCamera > b._distanceToCamera) {
  76813. return -1;
  76814. }
  76815. return 0;
  76816. });
  76817. // Render sub meshes
  76818. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  76819. for (index = 0; index < sortedArray.length; index++) {
  76820. renderSubMesh(sortedArray[index]);
  76821. }
  76822. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76823. }
  76824. };
  76825. };
  76826. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  76827. var transform = scene.getTransformMatrix();
  76828. var meshPosition;
  76829. if (this.useCustomMeshPosition) {
  76830. meshPosition = this.customMeshPosition;
  76831. }
  76832. else if (this.attachedNode) {
  76833. meshPosition = this.attachedNode.position;
  76834. }
  76835. else {
  76836. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  76837. }
  76838. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  76839. this._screenCoordinates.x = pos.x / this._viewPort.width;
  76840. this._screenCoordinates.y = pos.y / this._viewPort.height;
  76841. if (this.invert)
  76842. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  76843. };
  76844. // Static methods
  76845. /**
  76846. * Creates a default mesh for the Volumeric Light Scattering post-process
  76847. * @param {string} The mesh name
  76848. * @param {BABYLON.Scene} The scene where to create the mesh
  76849. * @return {BABYLON.Mesh} the default mesh
  76850. */
  76851. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  76852. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  76853. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  76854. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  76855. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  76856. mesh.material = material;
  76857. return mesh;
  76858. };
  76859. __decorate([
  76860. BABYLON.serializeAsVector3()
  76861. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  76862. __decorate([
  76863. BABYLON.serialize()
  76864. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  76865. __decorate([
  76866. BABYLON.serialize()
  76867. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  76868. __decorate([
  76869. BABYLON.serializeAsMeshReference()
  76870. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  76871. __decorate([
  76872. BABYLON.serialize()
  76873. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  76874. __decorate([
  76875. BABYLON.serialize()
  76876. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  76877. __decorate([
  76878. BABYLON.serialize()
  76879. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  76880. __decorate([
  76881. BABYLON.serialize()
  76882. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  76883. __decorate([
  76884. BABYLON.serialize()
  76885. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  76886. return VolumetricLightScatteringPostProcess;
  76887. }(BABYLON.PostProcess));
  76888. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  76889. })(BABYLON || (BABYLON = {}));
  76890. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  76891. //
  76892. // This post-process allows the modification of rendered colors by using
  76893. // a 'look-up table' (LUT). This effect is also called Color Grading.
  76894. //
  76895. // The object needs to be provided an url to a texture containing the color
  76896. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  76897. // Use an image editing software to tweak the LUT to match your needs.
  76898. //
  76899. // For an example of a color LUT, see here:
  76900. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  76901. // For explanations on color grading, see here:
  76902. // http://udn.epicgames.com/Three/ColorGrading.html
  76903. //
  76904. var BABYLON;
  76905. (function (BABYLON) {
  76906. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  76907. __extends(ColorCorrectionPostProcess, _super);
  76908. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  76909. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  76910. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76911. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  76912. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76913. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76914. _this.onApply = function (effect) {
  76915. effect.setTexture("colorTable", _this._colorTableTexture);
  76916. };
  76917. return _this;
  76918. }
  76919. return ColorCorrectionPostProcess;
  76920. }(BABYLON.PostProcess));
  76921. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  76922. })(BABYLON || (BABYLON = {}));
  76923. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  76924. var BABYLON;
  76925. (function (BABYLON) {
  76926. /** Defines operator used for tonemapping */
  76927. var TonemappingOperator;
  76928. (function (TonemappingOperator) {
  76929. /** Hable */
  76930. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  76931. /** Reinhard */
  76932. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  76933. /** HejiDawson */
  76934. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  76935. /** Photographic */
  76936. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  76937. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  76938. ;
  76939. /**
  76940. * Defines a post process to apply tone mapping
  76941. */
  76942. var TonemapPostProcess = /** @class */ (function (_super) {
  76943. __extends(TonemapPostProcess, _super);
  76944. /**
  76945. * Creates a new TonemapPostProcess
  76946. * @param name defines the name of the postprocess
  76947. * @param _operator defines the operator to use
  76948. * @param exposureAdjustment defines the required exposure adjustement
  76949. * @param camera defines the camera to use (can be null)
  76950. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  76951. * @param engine defines the hosting engine (can be ignore if camera is set)
  76952. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  76953. */
  76954. function TonemapPostProcess(name, _operator,
  76955. /** Defines the required exposure adjustement */
  76956. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  76957. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76958. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76959. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  76960. _this._operator = _operator;
  76961. _this.exposureAdjustment = exposureAdjustment;
  76962. var defines = "#define ";
  76963. if (_this._operator === TonemappingOperator.Hable)
  76964. defines += "HABLE_TONEMAPPING";
  76965. else if (_this._operator === TonemappingOperator.Reinhard)
  76966. defines += "REINHARD_TONEMAPPING";
  76967. else if (_this._operator === TonemappingOperator.HejiDawson)
  76968. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  76969. else if (_this._operator === TonemappingOperator.Photographic)
  76970. defines += "PHOTOGRAPHIC_TONEMAPPING";
  76971. //sadly a second call to create the effect.
  76972. _this.updateEffect(defines);
  76973. _this.onApply = function (effect) {
  76974. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  76975. };
  76976. return _this;
  76977. }
  76978. return TonemapPostProcess;
  76979. }(BABYLON.PostProcess));
  76980. BABYLON.TonemapPostProcess = TonemapPostProcess;
  76981. })(BABYLON || (BABYLON = {}));
  76982. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  76983. var BABYLON;
  76984. (function (BABYLON) {
  76985. var DisplayPassPostProcess = /** @class */ (function (_super) {
  76986. __extends(DisplayPassPostProcess, _super);
  76987. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  76988. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  76989. }
  76990. return DisplayPassPostProcess;
  76991. }(BABYLON.PostProcess));
  76992. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  76993. })(BABYLON || (BABYLON = {}));
  76994. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  76995. var BABYLON;
  76996. (function (BABYLON) {
  76997. var HighlightsPostProcess = /** @class */ (function (_super) {
  76998. __extends(HighlightsPostProcess, _super);
  76999. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77000. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77001. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77002. }
  77003. return HighlightsPostProcess;
  77004. }(BABYLON.PostProcess));
  77005. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77006. })(BABYLON || (BABYLON = {}));
  77007. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77008. var BABYLON;
  77009. (function (BABYLON) {
  77010. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77011. __extends(ImageProcessingPostProcess, _super);
  77012. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77013. if (camera === void 0) { camera = null; }
  77014. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77015. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77016. _this._fromLinearSpace = true;
  77017. /**
  77018. * Defines cache preventing GC.
  77019. */
  77020. _this._defines = {
  77021. IMAGEPROCESSING: false,
  77022. VIGNETTE: false,
  77023. VIGNETTEBLENDMODEMULTIPLY: false,
  77024. VIGNETTEBLENDMODEOPAQUE: false,
  77025. TONEMAPPING: false,
  77026. CONTRAST: false,
  77027. COLORCURVES: false,
  77028. COLORGRADING: false,
  77029. COLORGRADING3D: false,
  77030. FROMLINEARSPACE: false,
  77031. SAMPLER3DGREENDEPTH: false,
  77032. SAMPLER3DBGRMAP: false,
  77033. IMAGEPROCESSINGPOSTPROCESS: false,
  77034. EXPOSURE: false,
  77035. };
  77036. // Setup the configuration as forced by the constructor. This would then not force the
  77037. // scene materials output in linear space and let untouched the default forward pass.
  77038. if (imageProcessingConfiguration) {
  77039. imageProcessingConfiguration.applyByPostProcess = true;
  77040. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77041. // This will cause the shader to be compiled
  77042. _this.fromLinearSpace = false;
  77043. }
  77044. // Setup the default processing configuration to the scene.
  77045. else {
  77046. _this._attachImageProcessingConfiguration(null, true);
  77047. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77048. }
  77049. _this.onApply = function (effect) {
  77050. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77051. };
  77052. return _this;
  77053. }
  77054. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77055. /**
  77056. * Gets the image processing configuration used either in this material.
  77057. */
  77058. get: function () {
  77059. return this._imageProcessingConfiguration;
  77060. },
  77061. /**
  77062. * Sets the Default image processing configuration used either in the this material.
  77063. *
  77064. * If sets to null, the scene one is in use.
  77065. */
  77066. set: function (value) {
  77067. this._attachImageProcessingConfiguration(value);
  77068. },
  77069. enumerable: true,
  77070. configurable: true
  77071. });
  77072. /**
  77073. * Attaches a new image processing configuration to the PBR Material.
  77074. * @param configuration
  77075. */
  77076. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77077. var _this = this;
  77078. if (doNotBuild === void 0) { doNotBuild = false; }
  77079. if (configuration === this._imageProcessingConfiguration) {
  77080. return;
  77081. }
  77082. // Detaches observer.
  77083. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77084. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77085. }
  77086. // Pick the scene configuration if needed.
  77087. if (!configuration) {
  77088. var scene = null;
  77089. var engine = this.getEngine();
  77090. var camera = this.getCamera();
  77091. if (camera) {
  77092. scene = camera.getScene();
  77093. }
  77094. else if (engine && engine.scenes) {
  77095. var scenes = engine.scenes;
  77096. scene = scenes[scenes.length - 1];
  77097. }
  77098. else {
  77099. scene = BABYLON.Engine.LastCreatedScene;
  77100. }
  77101. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77102. }
  77103. else {
  77104. this._imageProcessingConfiguration = configuration;
  77105. }
  77106. // Attaches observer.
  77107. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77108. _this._updateParameters();
  77109. });
  77110. // Ensure the effect will be rebuilt.
  77111. if (!doNotBuild) {
  77112. this._updateParameters();
  77113. }
  77114. };
  77115. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77116. /**
  77117. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77118. */
  77119. get: function () {
  77120. return this.imageProcessingConfiguration.colorCurves;
  77121. },
  77122. /**
  77123. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77124. */
  77125. set: function (value) {
  77126. this.imageProcessingConfiguration.colorCurves = value;
  77127. },
  77128. enumerable: true,
  77129. configurable: true
  77130. });
  77131. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77132. /**
  77133. * Gets wether the color curves effect is enabled.
  77134. */
  77135. get: function () {
  77136. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77137. },
  77138. /**
  77139. * Sets wether the color curves effect is enabled.
  77140. */
  77141. set: function (value) {
  77142. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77143. },
  77144. enumerable: true,
  77145. configurable: true
  77146. });
  77147. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77148. /**
  77149. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77150. */
  77151. get: function () {
  77152. return this.imageProcessingConfiguration.colorGradingTexture;
  77153. },
  77154. /**
  77155. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77156. */
  77157. set: function (value) {
  77158. this.imageProcessingConfiguration.colorGradingTexture = value;
  77159. },
  77160. enumerable: true,
  77161. configurable: true
  77162. });
  77163. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77164. /**
  77165. * Gets wether the color grading effect is enabled.
  77166. */
  77167. get: function () {
  77168. return this.imageProcessingConfiguration.colorGradingEnabled;
  77169. },
  77170. /**
  77171. * Gets wether the color grading effect is enabled.
  77172. */
  77173. set: function (value) {
  77174. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77175. },
  77176. enumerable: true,
  77177. configurable: true
  77178. });
  77179. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77180. /**
  77181. * Gets exposure used in the effect.
  77182. */
  77183. get: function () {
  77184. return this.imageProcessingConfiguration.exposure;
  77185. },
  77186. /**
  77187. * Sets exposure used in the effect.
  77188. */
  77189. set: function (value) {
  77190. this.imageProcessingConfiguration.exposure = value;
  77191. },
  77192. enumerable: true,
  77193. configurable: true
  77194. });
  77195. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77196. /**
  77197. * Gets wether tonemapping is enabled or not.
  77198. */
  77199. get: function () {
  77200. return this._imageProcessingConfiguration.toneMappingEnabled;
  77201. },
  77202. /**
  77203. * Sets wether tonemapping is enabled or not
  77204. */
  77205. set: function (value) {
  77206. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77207. },
  77208. enumerable: true,
  77209. configurable: true
  77210. });
  77211. ;
  77212. ;
  77213. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77214. /**
  77215. * Gets contrast used in the effect.
  77216. */
  77217. get: function () {
  77218. return this.imageProcessingConfiguration.contrast;
  77219. },
  77220. /**
  77221. * Sets contrast used in the effect.
  77222. */
  77223. set: function (value) {
  77224. this.imageProcessingConfiguration.contrast = value;
  77225. },
  77226. enumerable: true,
  77227. configurable: true
  77228. });
  77229. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77230. /**
  77231. * Gets Vignette stretch size.
  77232. */
  77233. get: function () {
  77234. return this.imageProcessingConfiguration.vignetteStretch;
  77235. },
  77236. /**
  77237. * Sets Vignette stretch size.
  77238. */
  77239. set: function (value) {
  77240. this.imageProcessingConfiguration.vignetteStretch = value;
  77241. },
  77242. enumerable: true,
  77243. configurable: true
  77244. });
  77245. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77246. /**
  77247. * Gets Vignette centre X Offset.
  77248. */
  77249. get: function () {
  77250. return this.imageProcessingConfiguration.vignetteCentreX;
  77251. },
  77252. /**
  77253. * Sets Vignette centre X Offset.
  77254. */
  77255. set: function (value) {
  77256. this.imageProcessingConfiguration.vignetteCentreX = value;
  77257. },
  77258. enumerable: true,
  77259. configurable: true
  77260. });
  77261. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77262. /**
  77263. * Gets Vignette centre Y Offset.
  77264. */
  77265. get: function () {
  77266. return this.imageProcessingConfiguration.vignetteCentreY;
  77267. },
  77268. /**
  77269. * Sets Vignette centre Y Offset.
  77270. */
  77271. set: function (value) {
  77272. this.imageProcessingConfiguration.vignetteCentreY = value;
  77273. },
  77274. enumerable: true,
  77275. configurable: true
  77276. });
  77277. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77278. /**
  77279. * Gets Vignette weight or intensity of the vignette effect.
  77280. */
  77281. get: function () {
  77282. return this.imageProcessingConfiguration.vignetteWeight;
  77283. },
  77284. /**
  77285. * Sets Vignette weight or intensity of the vignette effect.
  77286. */
  77287. set: function (value) {
  77288. this.imageProcessingConfiguration.vignetteWeight = value;
  77289. },
  77290. enumerable: true,
  77291. configurable: true
  77292. });
  77293. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77294. /**
  77295. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77296. * if vignetteEnabled is set to true.
  77297. */
  77298. get: function () {
  77299. return this.imageProcessingConfiguration.vignetteColor;
  77300. },
  77301. /**
  77302. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77303. * if vignetteEnabled is set to true.
  77304. */
  77305. set: function (value) {
  77306. this.imageProcessingConfiguration.vignetteColor = value;
  77307. },
  77308. enumerable: true,
  77309. configurable: true
  77310. });
  77311. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77312. /**
  77313. * Gets Camera field of view used by the Vignette effect.
  77314. */
  77315. get: function () {
  77316. return this.imageProcessingConfiguration.vignetteCameraFov;
  77317. },
  77318. /**
  77319. * Sets Camera field of view used by the Vignette effect.
  77320. */
  77321. set: function (value) {
  77322. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77323. },
  77324. enumerable: true,
  77325. configurable: true
  77326. });
  77327. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77328. /**
  77329. * Gets the vignette blend mode allowing different kind of effect.
  77330. */
  77331. get: function () {
  77332. return this.imageProcessingConfiguration.vignetteBlendMode;
  77333. },
  77334. /**
  77335. * Sets the vignette blend mode allowing different kind of effect.
  77336. */
  77337. set: function (value) {
  77338. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77339. },
  77340. enumerable: true,
  77341. configurable: true
  77342. });
  77343. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77344. /**
  77345. * Gets wether the vignette effect is enabled.
  77346. */
  77347. get: function () {
  77348. return this.imageProcessingConfiguration.vignetteEnabled;
  77349. },
  77350. /**
  77351. * Sets wether the vignette effect is enabled.
  77352. */
  77353. set: function (value) {
  77354. this.imageProcessingConfiguration.vignetteEnabled = value;
  77355. },
  77356. enumerable: true,
  77357. configurable: true
  77358. });
  77359. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77360. /**
  77361. * Gets wether the input of the processing is in Gamma or Linear Space.
  77362. */
  77363. get: function () {
  77364. return this._fromLinearSpace;
  77365. },
  77366. /**
  77367. * Sets wether the input of the processing is in Gamma or Linear Space.
  77368. */
  77369. set: function (value) {
  77370. if (this._fromLinearSpace === value) {
  77371. return;
  77372. }
  77373. this._fromLinearSpace = value;
  77374. this._updateParameters();
  77375. },
  77376. enumerable: true,
  77377. configurable: true
  77378. });
  77379. ImageProcessingPostProcess.prototype.getClassName = function () {
  77380. return "ImageProcessingPostProcess";
  77381. };
  77382. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77383. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77384. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77385. var defines = "";
  77386. for (var define in this._defines) {
  77387. if (this._defines[define]) {
  77388. defines += "#define " + define + ";\r\n";
  77389. }
  77390. }
  77391. var samplers = ["textureSampler"];
  77392. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77393. var uniforms = ["scale"];
  77394. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77395. this.updateEffect(defines, uniforms, samplers);
  77396. };
  77397. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77398. _super.prototype.dispose.call(this, camera);
  77399. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77400. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77401. }
  77402. this.imageProcessingConfiguration.applyByPostProcess = false;
  77403. };
  77404. __decorate([
  77405. BABYLON.serialize()
  77406. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77407. return ImageProcessingPostProcess;
  77408. }(BABYLON.PostProcess));
  77409. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77410. })(BABYLON || (BABYLON = {}));
  77411. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77412. var BABYLON;
  77413. (function (BABYLON) {
  77414. /**
  77415. * Class used to store bone information
  77416. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77417. */
  77418. var Bone = /** @class */ (function (_super) {
  77419. __extends(Bone, _super);
  77420. /**
  77421. * Create a new bone
  77422. * @param name defines the bone name
  77423. * @param skeleton defines the parent skeleton
  77424. * @param parentBone defines the parent (can be null if the bone is the root)
  77425. * @param localMatrix defines the local matrix
  77426. * @param restPose defines the rest pose matrix
  77427. * @param baseMatrix defines the base matrix
  77428. * @param index defines index of the bone in the hiearchy
  77429. */
  77430. function Bone(
  77431. /**
  77432. * defines the bone name
  77433. */
  77434. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77435. if (parentBone === void 0) { parentBone = null; }
  77436. if (localMatrix === void 0) { localMatrix = null; }
  77437. if (restPose === void 0) { restPose = null; }
  77438. if (baseMatrix === void 0) { baseMatrix = null; }
  77439. if (index === void 0) { index = null; }
  77440. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77441. _this.name = name;
  77442. /**
  77443. * Gets the list of child bones
  77444. */
  77445. _this.children = new Array();
  77446. /** Gets the animations associated with this bone */
  77447. _this.animations = new Array();
  77448. /**
  77449. * @hidden Internal only
  77450. * Set this value to map this bone to a different index in the transform matrices
  77451. * Set this value to -1 to exclude the bone from the transform matrices
  77452. */
  77453. _this._index = null;
  77454. _this._absoluteTransform = new BABYLON.Matrix();
  77455. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77456. _this._scalingDeterminant = 1;
  77457. _this._worldTransform = new BABYLON.Matrix();
  77458. _this._needToDecompose = true;
  77459. _this._needToCompose = false;
  77460. _this._skeleton = skeleton;
  77461. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77462. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77463. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77464. _this._index = index;
  77465. skeleton.bones.push(_this);
  77466. _this.setParent(parentBone, false);
  77467. if (baseMatrix || localMatrix) {
  77468. _this._updateDifferenceMatrix();
  77469. }
  77470. return _this;
  77471. }
  77472. Object.defineProperty(Bone.prototype, "_matrix", {
  77473. /** @hidden */
  77474. get: function () {
  77475. this._compose();
  77476. return this._localMatrix;
  77477. },
  77478. /** @hidden */
  77479. set: function (value) {
  77480. this._localMatrix.copyFrom(value);
  77481. this._needToDecompose = true;
  77482. },
  77483. enumerable: true,
  77484. configurable: true
  77485. });
  77486. // Members
  77487. /**
  77488. * Gets the parent skeleton
  77489. * @returns a skeleton
  77490. */
  77491. Bone.prototype.getSkeleton = function () {
  77492. return this._skeleton;
  77493. };
  77494. /**
  77495. * Gets parent bone
  77496. * @returns a bone or null if the bone is the root of the bone hierarchy
  77497. */
  77498. Bone.prototype.getParent = function () {
  77499. return this._parent;
  77500. };
  77501. /**
  77502. * Sets the parent bone
  77503. * @param parent defines the parent (can be null if the bone is the root)
  77504. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77505. */
  77506. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  77507. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77508. if (this._parent === parent) {
  77509. return;
  77510. }
  77511. if (this._parent) {
  77512. var index = this._parent.children.indexOf(this);
  77513. if (index !== -1) {
  77514. this._parent.children.splice(index, 1);
  77515. }
  77516. }
  77517. this._parent = parent;
  77518. if (this._parent) {
  77519. this._parent.children.push(this);
  77520. }
  77521. if (updateDifferenceMatrix) {
  77522. this._updateDifferenceMatrix();
  77523. }
  77524. this.markAsDirty();
  77525. };
  77526. /**
  77527. * Gets the local matrix
  77528. * @returns a matrix
  77529. */
  77530. Bone.prototype.getLocalMatrix = function () {
  77531. this._compose();
  77532. return this._localMatrix;
  77533. };
  77534. /**
  77535. * Gets the base matrix (initial matrix which remains unchanged)
  77536. * @returns a matrix
  77537. */
  77538. Bone.prototype.getBaseMatrix = function () {
  77539. return this._baseMatrix;
  77540. };
  77541. /**
  77542. * Gets the rest pose matrix
  77543. * @returns a matrix
  77544. */
  77545. Bone.prototype.getRestPose = function () {
  77546. return this._restPose;
  77547. };
  77548. /**
  77549. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  77550. */
  77551. Bone.prototype.getWorldMatrix = function () {
  77552. return this._worldTransform;
  77553. };
  77554. /**
  77555. * Sets the local matrix to rest pose matrix
  77556. */
  77557. Bone.prototype.returnToRest = function () {
  77558. this.updateMatrix(this._restPose.clone());
  77559. };
  77560. /**
  77561. * Gets the inverse of the absolute transform matrix.
  77562. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  77563. * @returns a matrix
  77564. */
  77565. Bone.prototype.getInvertedAbsoluteTransform = function () {
  77566. return this._invertedAbsoluteTransform;
  77567. };
  77568. /**
  77569. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  77570. * @returns a matrix
  77571. */
  77572. Bone.prototype.getAbsoluteTransform = function () {
  77573. return this._absoluteTransform;
  77574. };
  77575. Object.defineProperty(Bone.prototype, "position", {
  77576. // Properties (matches AbstractMesh properties)
  77577. /** Gets or sets current position (in local space) */
  77578. get: function () {
  77579. this._decompose();
  77580. return this._localPosition;
  77581. },
  77582. set: function (newPosition) {
  77583. this._decompose();
  77584. this._localPosition.copyFrom(newPosition);
  77585. this._markAsDirtyAndCompose();
  77586. },
  77587. enumerable: true,
  77588. configurable: true
  77589. });
  77590. Object.defineProperty(Bone.prototype, "rotation", {
  77591. /** Gets or sets current rotation (in local space) */
  77592. get: function () {
  77593. return this.getRotation();
  77594. },
  77595. set: function (newRotation) {
  77596. this.setRotation(newRotation);
  77597. },
  77598. enumerable: true,
  77599. configurable: true
  77600. });
  77601. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  77602. /** Gets or sets current rotation quaternion (in local space) */
  77603. get: function () {
  77604. this._decompose();
  77605. return this._localRotation;
  77606. },
  77607. set: function (newRotation) {
  77608. this.setRotationQuaternion(newRotation);
  77609. },
  77610. enumerable: true,
  77611. configurable: true
  77612. });
  77613. Object.defineProperty(Bone.prototype, "scaling", {
  77614. /** Gets or sets current scaling (in local space) */
  77615. get: function () {
  77616. return this.getScale();
  77617. },
  77618. set: function (newScaling) {
  77619. this.setScale(newScaling);
  77620. },
  77621. enumerable: true,
  77622. configurable: true
  77623. });
  77624. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  77625. /**
  77626. * Gets the animation properties override
  77627. */
  77628. get: function () {
  77629. return this._skeleton.animationPropertiesOverride;
  77630. },
  77631. enumerable: true,
  77632. configurable: true
  77633. });
  77634. // Methods
  77635. Bone.prototype._decompose = function () {
  77636. if (!this._needToDecompose) {
  77637. return;
  77638. }
  77639. this._needToDecompose = false;
  77640. if (!this._localScaling) {
  77641. this._localScaling = BABYLON.Vector3.Zero();
  77642. this._localRotation = BABYLON.Quaternion.Zero();
  77643. this._localPosition = BABYLON.Vector3.Zero();
  77644. }
  77645. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  77646. };
  77647. Bone.prototype._compose = function () {
  77648. if (!this._needToCompose) {
  77649. return;
  77650. }
  77651. this._needToCompose = false;
  77652. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  77653. };
  77654. /**
  77655. * Update the base and local matrices
  77656. * @param matrix defines the new base or local matrix
  77657. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77658. * @param updateLocalMatrix defines if the local matrix should be updated
  77659. */
  77660. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  77661. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77662. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  77663. this._baseMatrix.copyFrom(matrix);
  77664. if (updateDifferenceMatrix) {
  77665. this._updateDifferenceMatrix();
  77666. }
  77667. if (updateLocalMatrix) {
  77668. this._localMatrix.copyFrom(matrix);
  77669. this._markAsDirtyAndDecompose();
  77670. }
  77671. else {
  77672. this.markAsDirty();
  77673. }
  77674. };
  77675. /** @hidden */
  77676. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  77677. if (updateChildren === void 0) { updateChildren = true; }
  77678. if (!rootMatrix) {
  77679. rootMatrix = this._baseMatrix;
  77680. }
  77681. if (this._parent) {
  77682. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77683. }
  77684. else {
  77685. this._absoluteTransform.copyFrom(rootMatrix);
  77686. }
  77687. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  77688. if (updateChildren) {
  77689. for (var index = 0; index < this.children.length; index++) {
  77690. this.children[index]._updateDifferenceMatrix();
  77691. }
  77692. }
  77693. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  77694. };
  77695. /**
  77696. * Flag the bone as dirty (Forcing it to update everything)
  77697. */
  77698. Bone.prototype.markAsDirty = function () {
  77699. this._currentRenderId++;
  77700. this._childRenderId++;
  77701. this._skeleton._markAsDirty();
  77702. };
  77703. Bone.prototype._markAsDirtyAndCompose = function () {
  77704. this.markAsDirty();
  77705. this._needToCompose = true;
  77706. };
  77707. Bone.prototype._markAsDirtyAndDecompose = function () {
  77708. this.markAsDirty();
  77709. this._needToDecompose = true;
  77710. };
  77711. /**
  77712. * Copy an animation range from another bone
  77713. * @param source defines the source bone
  77714. * @param rangeName defines the range name to copy
  77715. * @param frameOffset defines the frame offset
  77716. * @param rescaleAsRequired defines if rescaling must be applied if required
  77717. * @param skelDimensionsRatio defines the scaling ratio
  77718. * @returns true if operation was successful
  77719. */
  77720. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  77721. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77722. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  77723. // all animation may be coming from a library skeleton, so may need to create animation
  77724. if (this.animations.length === 0) {
  77725. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  77726. this.animations[0].setKeys([]);
  77727. }
  77728. // get animation info / verify there is such a range from the source bone
  77729. var sourceRange = source.animations[0].getRange(rangeName);
  77730. if (!sourceRange) {
  77731. return false;
  77732. }
  77733. var from = sourceRange.from;
  77734. var to = sourceRange.to;
  77735. var sourceKeys = source.animations[0].getKeys();
  77736. // rescaling prep
  77737. var sourceBoneLength = source.length;
  77738. var sourceParent = source.getParent();
  77739. var parent = this.getParent();
  77740. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  77741. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  77742. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  77743. var destKeys = this.animations[0].getKeys();
  77744. // loop vars declaration
  77745. var orig;
  77746. var origTranslation;
  77747. var mat;
  77748. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  77749. orig = sourceKeys[key];
  77750. if (orig.frame >= from && orig.frame <= to) {
  77751. if (rescaleAsRequired) {
  77752. mat = orig.value.clone();
  77753. // scale based on parent ratio, when bone has parent
  77754. if (parentScalingReqd) {
  77755. origTranslation = mat.getTranslation();
  77756. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  77757. // scale based on skeleton dimension ratio when root bone, and value is passed
  77758. }
  77759. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  77760. origTranslation = mat.getTranslation();
  77761. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77762. // use original when root bone, and no data for skelDimensionsRatio
  77763. }
  77764. else {
  77765. mat = orig.value;
  77766. }
  77767. }
  77768. else {
  77769. mat = orig.value;
  77770. }
  77771. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77772. }
  77773. }
  77774. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77775. return true;
  77776. };
  77777. /**
  77778. * Translate the bone in local or world space
  77779. * @param vec The amount to translate the bone
  77780. * @param space The space that the translation is in
  77781. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77782. */
  77783. Bone.prototype.translate = function (vec, space, mesh) {
  77784. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77785. var lm = this.getLocalMatrix();
  77786. if (space == BABYLON.Space.LOCAL) {
  77787. lm.m[12] += vec.x;
  77788. lm.m[13] += vec.y;
  77789. lm.m[14] += vec.z;
  77790. }
  77791. else {
  77792. var wm = null;
  77793. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77794. if (mesh) {
  77795. wm = mesh.getWorldMatrix();
  77796. }
  77797. this._skeleton.computeAbsoluteTransforms();
  77798. var tmat = Bone._tmpMats[0];
  77799. var tvec = Bone._tmpVecs[0];
  77800. if (this._parent) {
  77801. if (mesh && wm) {
  77802. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77803. tmat.multiplyToRef(wm, tmat);
  77804. }
  77805. else {
  77806. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77807. }
  77808. }
  77809. tmat.m[12] = 0;
  77810. tmat.m[13] = 0;
  77811. tmat.m[14] = 0;
  77812. tmat.invert();
  77813. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  77814. lm.m[12] += tvec.x;
  77815. lm.m[13] += tvec.y;
  77816. lm.m[14] += tvec.z;
  77817. }
  77818. this._markAsDirtyAndDecompose();
  77819. };
  77820. /**
  77821. * Set the postion of the bone in local or world space
  77822. * @param position The position to set the bone
  77823. * @param space The space that the position is in
  77824. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77825. */
  77826. Bone.prototype.setPosition = function (position, space, mesh) {
  77827. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77828. var lm = this.getLocalMatrix();
  77829. if (space == BABYLON.Space.LOCAL) {
  77830. lm.m[12] = position.x;
  77831. lm.m[13] = position.y;
  77832. lm.m[14] = position.z;
  77833. }
  77834. else {
  77835. var wm = null;
  77836. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77837. if (mesh) {
  77838. wm = mesh.getWorldMatrix();
  77839. }
  77840. this._skeleton.computeAbsoluteTransforms();
  77841. var tmat = Bone._tmpMats[0];
  77842. var vec = Bone._tmpVecs[0];
  77843. if (this._parent) {
  77844. if (mesh && wm) {
  77845. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77846. tmat.multiplyToRef(wm, tmat);
  77847. }
  77848. else {
  77849. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77850. }
  77851. }
  77852. tmat.invert();
  77853. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  77854. lm.m[12] = vec.x;
  77855. lm.m[13] = vec.y;
  77856. lm.m[14] = vec.z;
  77857. }
  77858. this._markAsDirtyAndDecompose();
  77859. };
  77860. /**
  77861. * Set the absolute position of the bone (world space)
  77862. * @param position The position to set the bone
  77863. * @param mesh The mesh that this bone is attached to
  77864. */
  77865. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  77866. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  77867. };
  77868. /**
  77869. * Scale the bone on the x, y and z axes (in local space)
  77870. * @param x The amount to scale the bone on the x axis
  77871. * @param y The amount to scale the bone on the y axis
  77872. * @param z The amount to scale the bone on the z axis
  77873. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  77874. */
  77875. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  77876. if (scaleChildren === void 0) { scaleChildren = false; }
  77877. var locMat = this.getLocalMatrix();
  77878. // Apply new scaling on top of current local matrix
  77879. var scaleMat = Bone._tmpMats[0];
  77880. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  77881. scaleMat.multiplyToRef(locMat, locMat);
  77882. // Invert scaling matrix and apply the inverse to all children
  77883. scaleMat.invert();
  77884. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  77885. var child = _a[_i];
  77886. var cm = child.getLocalMatrix();
  77887. cm.multiplyToRef(scaleMat, cm);
  77888. cm.m[12] *= x;
  77889. cm.m[13] *= y;
  77890. cm.m[14] *= z;
  77891. child._markAsDirtyAndDecompose();
  77892. }
  77893. this._markAsDirtyAndDecompose();
  77894. if (scaleChildren) {
  77895. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  77896. var child = _c[_b];
  77897. child.scale(x, y, z, scaleChildren);
  77898. }
  77899. }
  77900. };
  77901. /**
  77902. * Set the bone scaling in local space
  77903. * @param scale defines the scaling vector
  77904. */
  77905. Bone.prototype.setScale = function (scale) {
  77906. this._decompose();
  77907. this._localScaling.copyFrom(scale);
  77908. this._markAsDirtyAndCompose();
  77909. };
  77910. /**
  77911. * Gets the current scaling in local space
  77912. * @returns the current scaling vector
  77913. */
  77914. Bone.prototype.getScale = function () {
  77915. this._decompose();
  77916. return this._localScaling;
  77917. };
  77918. /**
  77919. * Gets the current scaling in local space and stores it in a target vector
  77920. * @param result defines the target vector
  77921. */
  77922. Bone.prototype.getScaleToRef = function (result) {
  77923. this._decompose();
  77924. result.copyFrom(this._localScaling);
  77925. };
  77926. /**
  77927. * Set the yaw, pitch, and roll of the bone in local or world space
  77928. * @param yaw The rotation of the bone on the y axis
  77929. * @param pitch The rotation of the bone on the x axis
  77930. * @param roll The rotation of the bone on the z axis
  77931. * @param space The space that the axes of rotation are in
  77932. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77933. */
  77934. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  77935. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77936. if (space === BABYLON.Space.LOCAL) {
  77937. var quat = Bone._tmpQuat;
  77938. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  77939. this.setRotationQuaternion(quat, space, mesh);
  77940. return;
  77941. }
  77942. var rotMatInv = Bone._tmpMats[0];
  77943. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77944. return;
  77945. }
  77946. var rotMat = Bone._tmpMats[1];
  77947. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  77948. rotMatInv.multiplyToRef(rotMat, rotMat);
  77949. this._rotateWithMatrix(rotMat, space, mesh);
  77950. };
  77951. /**
  77952. * Add a rotation to the bone on an axis in local or world space
  77953. * @param axis The axis to rotate the bone on
  77954. * @param amount The amount to rotate the bone
  77955. * @param space The space that the axis is in
  77956. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77957. */
  77958. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  77959. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77960. var rmat = Bone._tmpMats[0];
  77961. rmat.m[12] = 0;
  77962. rmat.m[13] = 0;
  77963. rmat.m[14] = 0;
  77964. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  77965. this._rotateWithMatrix(rmat, space, mesh);
  77966. };
  77967. /**
  77968. * Set the rotation of the bone to a particular axis angle in local or world space
  77969. * @param axis The axis to rotate the bone on
  77970. * @param angle The angle that the bone should be rotated to
  77971. * @param space The space that the axis is in
  77972. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77973. */
  77974. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  77975. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77976. if (space === BABYLON.Space.LOCAL) {
  77977. var quat = Bone._tmpQuat;
  77978. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  77979. this.setRotationQuaternion(quat, space, mesh);
  77980. return;
  77981. }
  77982. var rotMatInv = Bone._tmpMats[0];
  77983. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77984. return;
  77985. }
  77986. var rotMat = Bone._tmpMats[1];
  77987. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  77988. rotMatInv.multiplyToRef(rotMat, rotMat);
  77989. this._rotateWithMatrix(rotMat, space, mesh);
  77990. };
  77991. /**
  77992. * Set the euler rotation of the bone in local of world space
  77993. * @param rotation The euler rotation that the bone should be set to
  77994. * @param space The space that the rotation is in
  77995. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77996. */
  77997. Bone.prototype.setRotation = function (rotation, space, mesh) {
  77998. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77999. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78000. };
  78001. /**
  78002. * Set the quaternion rotation of the bone in local of world space
  78003. * @param quat The quaternion rotation that the bone should be set to
  78004. * @param space The space that the rotation is in
  78005. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78006. */
  78007. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78008. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78009. if (space === BABYLON.Space.LOCAL) {
  78010. this._decompose();
  78011. this._localRotation.copyFrom(quat);
  78012. this._markAsDirtyAndCompose();
  78013. return;
  78014. }
  78015. var rotMatInv = Bone._tmpMats[0];
  78016. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78017. return;
  78018. }
  78019. var rotMat = Bone._tmpMats[1];
  78020. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78021. rotMatInv.multiplyToRef(rotMat, rotMat);
  78022. this._rotateWithMatrix(rotMat, space, mesh);
  78023. };
  78024. /**
  78025. * Set the rotation matrix of the bone in local of world space
  78026. * @param rotMat The rotation matrix that the bone should be set to
  78027. * @param space The space that the rotation is in
  78028. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78029. */
  78030. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78031. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78032. if (space === BABYLON.Space.LOCAL) {
  78033. var quat = Bone._tmpQuat;
  78034. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78035. this.setRotationQuaternion(quat, space, mesh);
  78036. return;
  78037. }
  78038. var rotMatInv = Bone._tmpMats[0];
  78039. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78040. return;
  78041. }
  78042. var rotMat2 = Bone._tmpMats[1];
  78043. rotMat2.copyFrom(rotMat);
  78044. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78045. this._rotateWithMatrix(rotMat2, space, mesh);
  78046. };
  78047. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78048. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78049. var lmat = this.getLocalMatrix();
  78050. var lx = lmat.m[12];
  78051. var ly = lmat.m[13];
  78052. var lz = lmat.m[14];
  78053. var parent = this.getParent();
  78054. var parentScale = Bone._tmpMats[3];
  78055. var parentScaleInv = Bone._tmpMats[4];
  78056. if (parent && space == BABYLON.Space.WORLD) {
  78057. if (mesh) {
  78058. parentScale.copyFrom(mesh.getWorldMatrix());
  78059. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78060. }
  78061. else {
  78062. parentScale.copyFrom(parent.getAbsoluteTransform());
  78063. }
  78064. parentScaleInv.copyFrom(parentScale);
  78065. parentScaleInv.invert();
  78066. lmat.multiplyToRef(parentScale, lmat);
  78067. lmat.multiplyToRef(rmat, lmat);
  78068. lmat.multiplyToRef(parentScaleInv, lmat);
  78069. }
  78070. else {
  78071. if (space == BABYLON.Space.WORLD && mesh) {
  78072. parentScale.copyFrom(mesh.getWorldMatrix());
  78073. parentScaleInv.copyFrom(parentScale);
  78074. parentScaleInv.invert();
  78075. lmat.multiplyToRef(parentScale, lmat);
  78076. lmat.multiplyToRef(rmat, lmat);
  78077. lmat.multiplyToRef(parentScaleInv, lmat);
  78078. }
  78079. else {
  78080. lmat.multiplyToRef(rmat, lmat);
  78081. }
  78082. }
  78083. lmat.m[12] = lx;
  78084. lmat.m[13] = ly;
  78085. lmat.m[14] = lz;
  78086. this.computeAbsoluteTransforms();
  78087. this._markAsDirtyAndDecompose();
  78088. };
  78089. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78090. var scaleMatrix = Bone._tmpMats[2];
  78091. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78092. if (mesh) {
  78093. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78094. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78095. }
  78096. rotMatInv.invert();
  78097. if (isNaN(rotMatInv.m[0])) {
  78098. // Matrix failed to invert.
  78099. // This can happen if scale is zero for example.
  78100. return false;
  78101. }
  78102. scaleMatrix.m[0] *= this._scalingDeterminant;
  78103. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78104. return true;
  78105. };
  78106. /**
  78107. * Get the position of the bone in local or world space
  78108. * @param space The space that the returned position is in
  78109. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78110. * @returns The position of the bone
  78111. */
  78112. Bone.prototype.getPosition = function (space, mesh) {
  78113. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78114. if (mesh === void 0) { mesh = null; }
  78115. var pos = BABYLON.Vector3.Zero();
  78116. this.getPositionToRef(space, mesh, pos);
  78117. return pos;
  78118. };
  78119. /**
  78120. * Copy the position of the bone to a vector3 in local or world space
  78121. * @param space The space that the returned position is in
  78122. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78123. * @param result The vector3 to copy the position to
  78124. */
  78125. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78126. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78127. if (space == BABYLON.Space.LOCAL) {
  78128. var lm = this.getLocalMatrix();
  78129. result.x = lm.m[12];
  78130. result.y = lm.m[13];
  78131. result.z = lm.m[14];
  78132. }
  78133. else {
  78134. var wm = null;
  78135. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78136. if (mesh) {
  78137. wm = mesh.getWorldMatrix();
  78138. }
  78139. this._skeleton.computeAbsoluteTransforms();
  78140. var tmat = Bone._tmpMats[0];
  78141. if (mesh && wm) {
  78142. tmat.copyFrom(this.getAbsoluteTransform());
  78143. tmat.multiplyToRef(wm, tmat);
  78144. }
  78145. else {
  78146. tmat = this.getAbsoluteTransform();
  78147. }
  78148. result.x = tmat.m[12];
  78149. result.y = tmat.m[13];
  78150. result.z = tmat.m[14];
  78151. }
  78152. };
  78153. /**
  78154. * Get the absolute position of the bone (world space)
  78155. * @param mesh The mesh that this bone is attached to
  78156. * @returns The absolute position of the bone
  78157. */
  78158. Bone.prototype.getAbsolutePosition = function (mesh) {
  78159. if (mesh === void 0) { mesh = null; }
  78160. var pos = BABYLON.Vector3.Zero();
  78161. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78162. return pos;
  78163. };
  78164. /**
  78165. * Copy the absolute position of the bone (world space) to the result param
  78166. * @param mesh The mesh that this bone is attached to
  78167. * @param result The vector3 to copy the absolute position to
  78168. */
  78169. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78170. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78171. };
  78172. /**
  78173. * Compute the absolute transforms of this bone and its children
  78174. */
  78175. Bone.prototype.computeAbsoluteTransforms = function () {
  78176. this._compose();
  78177. if (this._parent) {
  78178. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78179. }
  78180. else {
  78181. this._absoluteTransform.copyFrom(this._localMatrix);
  78182. var poseMatrix = this._skeleton.getPoseMatrix();
  78183. if (poseMatrix) {
  78184. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78185. }
  78186. }
  78187. var children = this.children;
  78188. var len = children.length;
  78189. for (var i = 0; i < len; i++) {
  78190. children[i].computeAbsoluteTransforms();
  78191. }
  78192. };
  78193. /**
  78194. * Get the world direction from an axis that is in the local space of the bone
  78195. * @param localAxis The local direction that is used to compute the world direction
  78196. * @param mesh The mesh that this bone is attached to
  78197. * @returns The world direction
  78198. */
  78199. Bone.prototype.getDirection = function (localAxis, mesh) {
  78200. if (mesh === void 0) { mesh = null; }
  78201. var result = BABYLON.Vector3.Zero();
  78202. this.getDirectionToRef(localAxis, mesh, result);
  78203. return result;
  78204. };
  78205. /**
  78206. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78207. * @param localAxis The local direction that is used to compute the world direction
  78208. * @param mesh The mesh that this bone is attached to
  78209. * @param result The vector3 that the world direction will be copied to
  78210. */
  78211. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78212. if (mesh === void 0) { mesh = null; }
  78213. var wm = null;
  78214. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78215. if (mesh) {
  78216. wm = mesh.getWorldMatrix();
  78217. }
  78218. this._skeleton.computeAbsoluteTransforms();
  78219. var mat = Bone._tmpMats[0];
  78220. mat.copyFrom(this.getAbsoluteTransform());
  78221. if (mesh && wm) {
  78222. mat.multiplyToRef(wm, mat);
  78223. }
  78224. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78225. result.normalize();
  78226. };
  78227. /**
  78228. * Get the euler rotation of the bone in local or world space
  78229. * @param space The space that the rotation should be in
  78230. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78231. * @returns The euler rotation
  78232. */
  78233. Bone.prototype.getRotation = function (space, mesh) {
  78234. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78235. if (mesh === void 0) { mesh = null; }
  78236. var result = BABYLON.Vector3.Zero();
  78237. this.getRotationToRef(space, mesh, result);
  78238. return result;
  78239. };
  78240. /**
  78241. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78242. * @param space The space that the rotation should be in
  78243. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78244. * @param result The vector3 that the rotation should be copied to
  78245. */
  78246. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78247. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78248. if (mesh === void 0) { mesh = null; }
  78249. var quat = Bone._tmpQuat;
  78250. this.getRotationQuaternionToRef(space, mesh, quat);
  78251. quat.toEulerAnglesToRef(result);
  78252. };
  78253. /**
  78254. * Get the quaternion rotation of the bone in either local or world space
  78255. * @param space The space that the rotation should be in
  78256. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78257. * @returns The quaternion rotation
  78258. */
  78259. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78260. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78261. if (mesh === void 0) { mesh = null; }
  78262. var result = BABYLON.Quaternion.Identity();
  78263. this.getRotationQuaternionToRef(space, mesh, result);
  78264. return result;
  78265. };
  78266. /**
  78267. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78268. * @param space The space that the rotation should be in
  78269. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78270. * @param result The quaternion that the rotation should be copied to
  78271. */
  78272. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78273. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78274. if (mesh === void 0) { mesh = null; }
  78275. if (space == BABYLON.Space.LOCAL) {
  78276. this._decompose();
  78277. result.copyFrom(this._localRotation);
  78278. }
  78279. else {
  78280. var mat = Bone._tmpMats[0];
  78281. var amat = this.getAbsoluteTransform();
  78282. if (mesh) {
  78283. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78284. }
  78285. else {
  78286. mat.copyFrom(amat);
  78287. }
  78288. mat.m[0] *= this._scalingDeterminant;
  78289. mat.m[1] *= this._scalingDeterminant;
  78290. mat.m[2] *= this._scalingDeterminant;
  78291. mat.decompose(undefined, result, undefined);
  78292. }
  78293. };
  78294. /**
  78295. * Get the rotation matrix of the bone in local or world space
  78296. * @param space The space that the rotation should be in
  78297. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78298. * @returns The rotation matrix
  78299. */
  78300. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78301. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78302. var result = BABYLON.Matrix.Identity();
  78303. this.getRotationMatrixToRef(space, mesh, result);
  78304. return result;
  78305. };
  78306. /**
  78307. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78308. * @param space The space that the rotation should be in
  78309. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78310. * @param result The quaternion that the rotation should be copied to
  78311. */
  78312. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78313. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78314. if (space == BABYLON.Space.LOCAL) {
  78315. this.getLocalMatrix().getRotationMatrixToRef(result);
  78316. }
  78317. else {
  78318. var mat = Bone._tmpMats[0];
  78319. var amat = this.getAbsoluteTransform();
  78320. if (mesh) {
  78321. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78322. }
  78323. else {
  78324. mat.copyFrom(amat);
  78325. }
  78326. mat.m[0] *= this._scalingDeterminant;
  78327. mat.m[1] *= this._scalingDeterminant;
  78328. mat.m[2] *= this._scalingDeterminant;
  78329. mat.getRotationMatrixToRef(result);
  78330. }
  78331. };
  78332. /**
  78333. * Get the world position of a point that is in the local space of the bone
  78334. * @param position The local position
  78335. * @param mesh The mesh that this bone is attached to
  78336. * @returns The world position
  78337. */
  78338. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78339. if (mesh === void 0) { mesh = null; }
  78340. var result = BABYLON.Vector3.Zero();
  78341. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78342. return result;
  78343. };
  78344. /**
  78345. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78346. * @param position The local position
  78347. * @param mesh The mesh that this bone is attached to
  78348. * @param result The vector3 that the world position should be copied to
  78349. */
  78350. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78351. if (mesh === void 0) { mesh = null; }
  78352. var wm = null;
  78353. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78354. if (mesh) {
  78355. wm = mesh.getWorldMatrix();
  78356. }
  78357. this._skeleton.computeAbsoluteTransforms();
  78358. var tmat = Bone._tmpMats[0];
  78359. if (mesh && wm) {
  78360. tmat.copyFrom(this.getAbsoluteTransform());
  78361. tmat.multiplyToRef(wm, tmat);
  78362. }
  78363. else {
  78364. tmat = this.getAbsoluteTransform();
  78365. }
  78366. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78367. };
  78368. /**
  78369. * Get the local position of a point that is in world space
  78370. * @param position The world position
  78371. * @param mesh The mesh that this bone is attached to
  78372. * @returns The local position
  78373. */
  78374. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78375. if (mesh === void 0) { mesh = null; }
  78376. var result = BABYLON.Vector3.Zero();
  78377. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78378. return result;
  78379. };
  78380. /**
  78381. * Get the local position of a point that is in world space and copy it to the result param
  78382. * @param position The world position
  78383. * @param mesh The mesh that this bone is attached to
  78384. * @param result The vector3 that the local position should be copied to
  78385. */
  78386. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78387. if (mesh === void 0) { mesh = null; }
  78388. var wm = null;
  78389. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78390. if (mesh) {
  78391. wm = mesh.getWorldMatrix();
  78392. }
  78393. this._skeleton.computeAbsoluteTransforms();
  78394. var tmat = Bone._tmpMats[0];
  78395. tmat.copyFrom(this.getAbsoluteTransform());
  78396. if (mesh && wm) {
  78397. tmat.multiplyToRef(wm, tmat);
  78398. }
  78399. tmat.invert();
  78400. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78401. };
  78402. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78403. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78404. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78405. return Bone;
  78406. }(BABYLON.Node));
  78407. BABYLON.Bone = Bone;
  78408. })(BABYLON || (BABYLON = {}));
  78409. //# sourceMappingURL=babylon.bone.js.map
  78410. var BABYLON;
  78411. (function (BABYLON) {
  78412. /**
  78413. * Class used to apply inverse kinematics to bones
  78414. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78415. */
  78416. var BoneIKController = /** @class */ (function () {
  78417. /**
  78418. * Creates a new BoneIKController
  78419. * @param mesh defines the mesh to control
  78420. * @param bone defines the bone to control
  78421. * @param options defines options to set up the controller
  78422. */
  78423. function BoneIKController(mesh, bone, options) {
  78424. /**
  78425. * Gets or sets the target position
  78426. */
  78427. this.targetPosition = BABYLON.Vector3.Zero();
  78428. /**
  78429. * Gets or sets the pole target position
  78430. */
  78431. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78432. /**
  78433. * Gets or sets the pole target local offset
  78434. */
  78435. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78436. /**
  78437. * Gets or sets the pole angle
  78438. */
  78439. this.poleAngle = 0;
  78440. /**
  78441. * 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)
  78442. */
  78443. this.slerpAmount = 1;
  78444. this._bone1Quat = BABYLON.Quaternion.Identity();
  78445. this._bone1Mat = BABYLON.Matrix.Identity();
  78446. this._bone2Ang = Math.PI;
  78447. this._maxAngle = Math.PI;
  78448. this._rightHandedSystem = false;
  78449. this._bendAxis = BABYLON.Vector3.Right();
  78450. this._slerping = false;
  78451. this._adjustRoll = 0;
  78452. this._bone2 = bone;
  78453. this._bone1 = bone.getParent();
  78454. if (!this._bone1) {
  78455. return;
  78456. }
  78457. this.mesh = mesh;
  78458. var bonePos = bone.getPosition();
  78459. if (bone.getAbsoluteTransform().determinant() > 0) {
  78460. this._rightHandedSystem = true;
  78461. this._bendAxis.x = 0;
  78462. this._bendAxis.y = 0;
  78463. this._bendAxis.z = -1;
  78464. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78465. this._adjustRoll = Math.PI * .5;
  78466. this._bendAxis.z = 1;
  78467. }
  78468. }
  78469. if (this._bone1.length) {
  78470. var boneScale1 = this._bone1.getScale();
  78471. var boneScale2 = this._bone2.getScale();
  78472. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78473. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78474. }
  78475. else if (this._bone1.children[0]) {
  78476. mesh.computeWorldMatrix(true);
  78477. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78478. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78479. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78480. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78481. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78482. }
  78483. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78484. this.maxAngle = Math.PI;
  78485. if (options) {
  78486. if (options.targetMesh) {
  78487. this.targetMesh = options.targetMesh;
  78488. this.targetMesh.computeWorldMatrix(true);
  78489. }
  78490. if (options.poleTargetMesh) {
  78491. this.poleTargetMesh = options.poleTargetMesh;
  78492. this.poleTargetMesh.computeWorldMatrix(true);
  78493. }
  78494. else if (options.poleTargetBone) {
  78495. this.poleTargetBone = options.poleTargetBone;
  78496. }
  78497. else if (this._bone1.getParent()) {
  78498. this.poleTargetBone = this._bone1.getParent();
  78499. }
  78500. if (options.poleTargetLocalOffset) {
  78501. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  78502. }
  78503. if (options.poleAngle) {
  78504. this.poleAngle = options.poleAngle;
  78505. }
  78506. if (options.bendAxis) {
  78507. this._bendAxis.copyFrom(options.bendAxis);
  78508. }
  78509. if (options.maxAngle) {
  78510. this.maxAngle = options.maxAngle;
  78511. }
  78512. if (options.slerpAmount) {
  78513. this.slerpAmount = options.slerpAmount;
  78514. }
  78515. }
  78516. }
  78517. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  78518. /**
  78519. * Gets or sets maximum allowed angle
  78520. */
  78521. get: function () {
  78522. return this._maxAngle;
  78523. },
  78524. set: function (value) {
  78525. this._setMaxAngle(value);
  78526. },
  78527. enumerable: true,
  78528. configurable: true
  78529. });
  78530. BoneIKController.prototype._setMaxAngle = function (ang) {
  78531. if (ang < 0) {
  78532. ang = 0;
  78533. }
  78534. if (ang > Math.PI || ang == undefined) {
  78535. ang = Math.PI;
  78536. }
  78537. this._maxAngle = ang;
  78538. var a = this._bone1Length;
  78539. var b = this._bone2Length;
  78540. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  78541. };
  78542. /**
  78543. * Force the controller to update the bones
  78544. */
  78545. BoneIKController.prototype.update = function () {
  78546. var bone1 = this._bone1;
  78547. if (!bone1) {
  78548. return;
  78549. }
  78550. var target = this.targetPosition;
  78551. var poleTarget = this.poleTargetPosition;
  78552. var mat1 = BoneIKController._tmpMats[0];
  78553. var mat2 = BoneIKController._tmpMats[1];
  78554. if (this.targetMesh) {
  78555. target.copyFrom(this.targetMesh.getAbsolutePosition());
  78556. }
  78557. if (this.poleTargetBone) {
  78558. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  78559. }
  78560. else if (this.poleTargetMesh) {
  78561. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  78562. }
  78563. var bonePos = BoneIKController._tmpVecs[0];
  78564. var zaxis = BoneIKController._tmpVecs[1];
  78565. var xaxis = BoneIKController._tmpVecs[2];
  78566. var yaxis = BoneIKController._tmpVecs[3];
  78567. var upAxis = BoneIKController._tmpVecs[4];
  78568. var _tmpQuat = BoneIKController._tmpQuat;
  78569. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  78570. poleTarget.subtractToRef(bonePos, upAxis);
  78571. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  78572. upAxis.y = 1;
  78573. }
  78574. else {
  78575. upAxis.normalize();
  78576. }
  78577. target.subtractToRef(bonePos, yaxis);
  78578. yaxis.normalize();
  78579. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  78580. zaxis.normalize();
  78581. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  78582. xaxis.normalize();
  78583. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  78584. var a = this._bone1Length;
  78585. var b = this._bone2Length;
  78586. var c = BABYLON.Vector3.Distance(bonePos, target);
  78587. if (this._maxReach > 0) {
  78588. c = Math.min(this._maxReach, c);
  78589. }
  78590. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  78591. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  78592. if (acosa > 1) {
  78593. acosa = 1;
  78594. }
  78595. if (acosb > 1) {
  78596. acosb = 1;
  78597. }
  78598. if (acosa < -1) {
  78599. acosa = -1;
  78600. }
  78601. if (acosb < -1) {
  78602. acosb = -1;
  78603. }
  78604. var angA = Math.acos(acosa);
  78605. var angB = Math.acos(acosb);
  78606. var angC = -angA - angB;
  78607. if (this._rightHandedSystem) {
  78608. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  78609. mat2.multiplyToRef(mat1, mat1);
  78610. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  78611. mat2.multiplyToRef(mat1, mat1);
  78612. }
  78613. else {
  78614. var _tmpVec = BoneIKController._tmpVecs[5];
  78615. _tmpVec.copyFrom(this._bendAxis);
  78616. _tmpVec.x *= -1;
  78617. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  78618. mat2.multiplyToRef(mat1, mat1);
  78619. }
  78620. if (this.poleAngle) {
  78621. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  78622. mat1.multiplyToRef(mat2, mat1);
  78623. }
  78624. if (this._bone1) {
  78625. if (this.slerpAmount < 1) {
  78626. if (!this._slerping) {
  78627. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  78628. }
  78629. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  78630. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  78631. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  78632. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  78633. this._slerping = true;
  78634. }
  78635. else {
  78636. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  78637. this._bone1Mat.copyFrom(mat1);
  78638. this._slerping = false;
  78639. }
  78640. }
  78641. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  78642. this._bone2Ang = angC;
  78643. };
  78644. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78645. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  78646. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78647. return BoneIKController;
  78648. }());
  78649. BABYLON.BoneIKController = BoneIKController;
  78650. })(BABYLON || (BABYLON = {}));
  78651. //# sourceMappingURL=babylon.boneIKController.js.map
  78652. var BABYLON;
  78653. (function (BABYLON) {
  78654. /**
  78655. * Class used to make a bone look toward a point in space
  78656. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  78657. */
  78658. var BoneLookController = /** @class */ (function () {
  78659. /**
  78660. * Create a BoneLookController
  78661. * @param mesh the mesh that the bone belongs to
  78662. * @param bone the bone that will be looking to the target
  78663. * @param target the target Vector3 to look at
  78664. * @param settings optional settings:
  78665. * * maxYaw: the maximum angle the bone will yaw to
  78666. * * minYaw: the minimum angle the bone will yaw to
  78667. * * maxPitch: the maximum angle the bone will pitch to
  78668. * * minPitch: the minimum angle the bone will yaw to
  78669. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  78670. * * upAxis: the up axis of the coordinate system
  78671. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  78672. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  78673. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  78674. * * adjustYaw: used to make an adjustment to the yaw of the bone
  78675. * * adjustPitch: used to make an adjustment to the pitch of the bone
  78676. * * adjustRoll: used to make an adjustment to the roll of the bone
  78677. **/
  78678. function BoneLookController(mesh, bone, target, options) {
  78679. /**
  78680. * The up axis of the coordinate system that is used when the bone is rotated
  78681. */
  78682. this.upAxis = BABYLON.Vector3.Up();
  78683. /**
  78684. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  78685. */
  78686. this.upAxisSpace = BABYLON.Space.LOCAL;
  78687. /**
  78688. * Used to make an adjustment to the yaw of the bone
  78689. */
  78690. this.adjustYaw = 0;
  78691. /**
  78692. * Used to make an adjustment to the pitch of the bone
  78693. */
  78694. this.adjustPitch = 0;
  78695. /**
  78696. * Used to make an adjustment to the roll of the bone
  78697. */
  78698. this.adjustRoll = 0;
  78699. /**
  78700. * 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)
  78701. */
  78702. this.slerpAmount = 1;
  78703. this._boneQuat = BABYLON.Quaternion.Identity();
  78704. this._slerping = false;
  78705. this._firstFrameSkipped = false;
  78706. this._fowardAxis = BABYLON.Vector3.Forward();
  78707. this.mesh = mesh;
  78708. this.bone = bone;
  78709. this.target = target;
  78710. if (options) {
  78711. if (options.adjustYaw) {
  78712. this.adjustYaw = options.adjustYaw;
  78713. }
  78714. if (options.adjustPitch) {
  78715. this.adjustPitch = options.adjustPitch;
  78716. }
  78717. if (options.adjustRoll) {
  78718. this.adjustRoll = options.adjustRoll;
  78719. }
  78720. if (options.maxYaw != null) {
  78721. this.maxYaw = options.maxYaw;
  78722. }
  78723. else {
  78724. this.maxYaw = Math.PI;
  78725. }
  78726. if (options.minYaw != null) {
  78727. this.minYaw = options.minYaw;
  78728. }
  78729. else {
  78730. this.minYaw = -Math.PI;
  78731. }
  78732. if (options.maxPitch != null) {
  78733. this.maxPitch = options.maxPitch;
  78734. }
  78735. else {
  78736. this.maxPitch = Math.PI;
  78737. }
  78738. if (options.minPitch != null) {
  78739. this.minPitch = options.minPitch;
  78740. }
  78741. else {
  78742. this.minPitch = -Math.PI;
  78743. }
  78744. if (options.slerpAmount != null) {
  78745. this.slerpAmount = options.slerpAmount;
  78746. }
  78747. if (options.upAxis != null) {
  78748. this.upAxis = options.upAxis;
  78749. }
  78750. if (options.upAxisSpace != null) {
  78751. this.upAxisSpace = options.upAxisSpace;
  78752. }
  78753. if (options.yawAxis != null || options.pitchAxis != null) {
  78754. var newYawAxis = BABYLON.Axis.Y;
  78755. var newPitchAxis = BABYLON.Axis.X;
  78756. if (options.yawAxis != null) {
  78757. newYawAxis = options.yawAxis.clone();
  78758. newYawAxis.normalize();
  78759. }
  78760. if (options.pitchAxis != null) {
  78761. newPitchAxis = options.pitchAxis.clone();
  78762. newPitchAxis.normalize();
  78763. }
  78764. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78765. this._transformYawPitch = BABYLON.Matrix.Identity();
  78766. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78767. this._transformYawPitchInv = this._transformYawPitch.clone();
  78768. this._transformYawPitch.invert();
  78769. }
  78770. }
  78771. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78772. this.upAxisSpace = BABYLON.Space.LOCAL;
  78773. }
  78774. }
  78775. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78776. /**
  78777. * Gets or sets the minimum yaw angle that the bone can look to
  78778. */
  78779. get: function () {
  78780. return this._minYaw;
  78781. },
  78782. set: function (value) {
  78783. this._minYaw = value;
  78784. this._minYawSin = Math.sin(value);
  78785. this._minYawCos = Math.cos(value);
  78786. if (this._maxYaw != null) {
  78787. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78788. this._yawRange = this._maxYaw - this._minYaw;
  78789. }
  78790. },
  78791. enumerable: true,
  78792. configurable: true
  78793. });
  78794. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  78795. /**
  78796. * Gets or sets the maximum yaw angle that the bone can look to
  78797. */
  78798. get: function () {
  78799. return this._maxYaw;
  78800. },
  78801. set: function (value) {
  78802. this._maxYaw = value;
  78803. this._maxYawSin = Math.sin(value);
  78804. this._maxYawCos = Math.cos(value);
  78805. if (this._minYaw != null) {
  78806. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78807. this._yawRange = this._maxYaw - this._minYaw;
  78808. }
  78809. },
  78810. enumerable: true,
  78811. configurable: true
  78812. });
  78813. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  78814. /**
  78815. * Gets or sets the minimum pitch angle that the bone can look to
  78816. */
  78817. get: function () {
  78818. return this._minPitch;
  78819. },
  78820. set: function (value) {
  78821. this._minPitch = value;
  78822. this._minPitchTan = Math.tan(value);
  78823. },
  78824. enumerable: true,
  78825. configurable: true
  78826. });
  78827. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  78828. /**
  78829. * Gets or sets the maximum pitch angle that the bone can look to
  78830. */
  78831. get: function () {
  78832. return this._maxPitch;
  78833. },
  78834. set: function (value) {
  78835. this._maxPitch = value;
  78836. this._maxPitchTan = Math.tan(value);
  78837. },
  78838. enumerable: true,
  78839. configurable: true
  78840. });
  78841. /**
  78842. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  78843. */
  78844. BoneLookController.prototype.update = function () {
  78845. //skip the first frame when slerping so that the mesh rotation is correct
  78846. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  78847. this._firstFrameSkipped = true;
  78848. return;
  78849. }
  78850. var bone = this.bone;
  78851. var bonePos = BoneLookController._tmpVecs[0];
  78852. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  78853. var target = this.target;
  78854. var _tmpMat1 = BoneLookController._tmpMats[0];
  78855. var _tmpMat2 = BoneLookController._tmpMats[1];
  78856. var mesh = this.mesh;
  78857. var parentBone = bone.getParent();
  78858. var upAxis = BoneLookController._tmpVecs[1];
  78859. upAxis.copyFrom(this.upAxis);
  78860. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  78861. if (this._transformYawPitch) {
  78862. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  78863. }
  78864. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  78865. }
  78866. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  78867. mesh.getDirectionToRef(upAxis, upAxis);
  78868. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  78869. upAxis.normalize();
  78870. }
  78871. }
  78872. var checkYaw = false;
  78873. var checkPitch = false;
  78874. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  78875. checkYaw = true;
  78876. }
  78877. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  78878. checkPitch = true;
  78879. }
  78880. if (checkYaw || checkPitch) {
  78881. var spaceMat = BoneLookController._tmpMats[2];
  78882. var spaceMatInv = BoneLookController._tmpMats[3];
  78883. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  78884. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  78885. }
  78886. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  78887. spaceMat.copyFrom(mesh.getWorldMatrix());
  78888. }
  78889. else {
  78890. var forwardAxis = BoneLookController._tmpVecs[2];
  78891. forwardAxis.copyFrom(this._fowardAxis);
  78892. if (this._transformYawPitch) {
  78893. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  78894. }
  78895. if (parentBone) {
  78896. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  78897. }
  78898. else {
  78899. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  78900. }
  78901. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  78902. rightAxis.normalize();
  78903. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  78904. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  78905. }
  78906. spaceMat.invertToRef(spaceMatInv);
  78907. var xzlen = null;
  78908. if (checkPitch) {
  78909. var localTarget = BoneLookController._tmpVecs[3];
  78910. target.subtractToRef(bonePos, localTarget);
  78911. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78912. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78913. var pitch = Math.atan2(localTarget.y, xzlen);
  78914. var newPitch = pitch;
  78915. if (pitch > this._maxPitch) {
  78916. localTarget.y = this._maxPitchTan * xzlen;
  78917. newPitch = this._maxPitch;
  78918. }
  78919. else if (pitch < this._minPitch) {
  78920. localTarget.y = this._minPitchTan * xzlen;
  78921. newPitch = this._minPitch;
  78922. }
  78923. if (pitch != newPitch) {
  78924. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78925. localTarget.addInPlace(bonePos);
  78926. target = localTarget;
  78927. }
  78928. }
  78929. if (checkYaw) {
  78930. var localTarget = BoneLookController._tmpVecs[4];
  78931. target.subtractToRef(bonePos, localTarget);
  78932. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78933. var yaw = Math.atan2(localTarget.x, localTarget.z);
  78934. var newYaw = yaw;
  78935. if (yaw > this._maxYaw || yaw < this._minYaw) {
  78936. if (xzlen == null) {
  78937. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78938. }
  78939. if (this._yawRange > Math.PI) {
  78940. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  78941. localTarget.z = this._maxYawCos * xzlen;
  78942. localTarget.x = this._maxYawSin * xzlen;
  78943. newYaw = this._maxYaw;
  78944. }
  78945. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  78946. localTarget.z = this._minYawCos * xzlen;
  78947. localTarget.x = this._minYawSin * xzlen;
  78948. newYaw = this._minYaw;
  78949. }
  78950. }
  78951. else {
  78952. if (yaw > this._maxYaw) {
  78953. localTarget.z = this._maxYawCos * xzlen;
  78954. localTarget.x = this._maxYawSin * xzlen;
  78955. newYaw = this._maxYaw;
  78956. }
  78957. else if (yaw < this._minYaw) {
  78958. localTarget.z = this._minYawCos * xzlen;
  78959. localTarget.x = this._minYawSin * xzlen;
  78960. newYaw = this._minYaw;
  78961. }
  78962. }
  78963. }
  78964. if (this._slerping && this._yawRange > Math.PI) {
  78965. //are we going to be crossing into the min/max region?
  78966. var boneFwd = BoneLookController._tmpVecs[8];
  78967. boneFwd.copyFrom(BABYLON.Axis.Z);
  78968. if (this._transformYawPitch) {
  78969. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  78970. }
  78971. var boneRotMat = BoneLookController._tmpMats[4];
  78972. this._boneQuat.toRotationMatrix(boneRotMat);
  78973. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  78974. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  78975. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  78976. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  78977. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  78978. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  78979. if (angBtwTar > angBtwMidYaw) {
  78980. if (xzlen == null) {
  78981. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78982. }
  78983. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  78984. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  78985. if (angBtwMin < angBtwMax) {
  78986. newYaw = boneYaw + Math.PI * .75;
  78987. localTarget.z = Math.cos(newYaw) * xzlen;
  78988. localTarget.x = Math.sin(newYaw) * xzlen;
  78989. }
  78990. else {
  78991. newYaw = boneYaw - Math.PI * .75;
  78992. localTarget.z = Math.cos(newYaw) * xzlen;
  78993. localTarget.x = Math.sin(newYaw) * xzlen;
  78994. }
  78995. }
  78996. }
  78997. if (yaw != newYaw) {
  78998. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78999. localTarget.addInPlace(bonePos);
  79000. target = localTarget;
  79001. }
  79002. }
  79003. }
  79004. var zaxis = BoneLookController._tmpVecs[5];
  79005. var xaxis = BoneLookController._tmpVecs[6];
  79006. var yaxis = BoneLookController._tmpVecs[7];
  79007. var _tmpQuat = BoneLookController._tmpQuat;
  79008. target.subtractToRef(bonePos, zaxis);
  79009. zaxis.normalize();
  79010. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79011. xaxis.normalize();
  79012. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79013. yaxis.normalize();
  79014. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79015. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79016. return;
  79017. }
  79018. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79019. return;
  79020. }
  79021. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79022. return;
  79023. }
  79024. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79025. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79026. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79027. }
  79028. if (this.slerpAmount < 1) {
  79029. if (!this._slerping) {
  79030. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79031. }
  79032. if (this._transformYawPitch) {
  79033. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79034. }
  79035. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79036. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79037. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79038. this._slerping = true;
  79039. }
  79040. else {
  79041. if (this._transformYawPitch) {
  79042. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79043. }
  79044. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79045. this._slerping = false;
  79046. }
  79047. };
  79048. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79049. var angDiff = ang2 - ang1;
  79050. angDiff %= Math.PI * 2;
  79051. if (angDiff > Math.PI) {
  79052. angDiff -= Math.PI * 2;
  79053. }
  79054. else if (angDiff < -Math.PI) {
  79055. angDiff += Math.PI * 2;
  79056. }
  79057. return angDiff;
  79058. };
  79059. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79060. ang1 %= (2 * Math.PI);
  79061. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79062. ang2 %= (2 * Math.PI);
  79063. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79064. var ab = 0;
  79065. if (ang1 < ang2) {
  79066. ab = ang2 - ang1;
  79067. }
  79068. else {
  79069. ab = ang1 - ang2;
  79070. }
  79071. if (ab > Math.PI) {
  79072. ab = Math.PI * 2 - ab;
  79073. }
  79074. return ab;
  79075. };
  79076. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79077. ang %= (2 * Math.PI);
  79078. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79079. ang1 %= (2 * Math.PI);
  79080. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79081. ang2 %= (2 * Math.PI);
  79082. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79083. if (ang1 < ang2) {
  79084. if (ang > ang1 && ang < ang2) {
  79085. return true;
  79086. }
  79087. }
  79088. else {
  79089. if (ang > ang2 && ang < ang1) {
  79090. return true;
  79091. }
  79092. }
  79093. return false;
  79094. };
  79095. 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()];
  79096. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79097. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79098. return BoneLookController;
  79099. }());
  79100. BABYLON.BoneLookController = BoneLookController;
  79101. })(BABYLON || (BABYLON = {}));
  79102. //# sourceMappingURL=babylon.boneLookController.js.map
  79103. var BABYLON;
  79104. (function (BABYLON) {
  79105. /**
  79106. * Class used to handle skinning animations
  79107. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79108. */
  79109. var Skeleton = /** @class */ (function () {
  79110. /**
  79111. * Creates a new skeleton
  79112. * @param name defines the skeleton name
  79113. * @param id defines the skeleton Id
  79114. * @param scene defines the hosting scene
  79115. */
  79116. function Skeleton(
  79117. /** defines the skeleton name */
  79118. name,
  79119. /** defines the skeleton Id */
  79120. id, scene) {
  79121. this.name = name;
  79122. this.id = id;
  79123. /**
  79124. * Gets the list of child bones
  79125. */
  79126. this.bones = new Array();
  79127. /**
  79128. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79129. */
  79130. this.needInitialSkinMatrix = false;
  79131. this._isDirty = true;
  79132. this._meshesWithPoseMatrix = new Array();
  79133. this._identity = BABYLON.Matrix.Identity();
  79134. this._ranges = {};
  79135. this._lastAbsoluteTransformsUpdateId = -1;
  79136. /**
  79137. * Specifies if the skeleton should be serialized
  79138. */
  79139. this.doNotSerialize = false;
  79140. this._animationPropertiesOverride = null;
  79141. // Events
  79142. /**
  79143. * An observable triggered before computing the skeleton's matrices
  79144. */
  79145. this.onBeforeComputeObservable = new BABYLON.Observable();
  79146. this.bones = [];
  79147. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79148. scene.skeletons.push(this);
  79149. //make sure it will recalculate the matrix next time prepare is called.
  79150. this._isDirty = true;
  79151. }
  79152. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79153. /**
  79154. * Gets or sets the animation properties override
  79155. */
  79156. get: function () {
  79157. if (!this._animationPropertiesOverride) {
  79158. return this._scene.animationPropertiesOverride;
  79159. }
  79160. return this._animationPropertiesOverride;
  79161. },
  79162. set: function (value) {
  79163. this._animationPropertiesOverride = value;
  79164. },
  79165. enumerable: true,
  79166. configurable: true
  79167. });
  79168. // Members
  79169. /**
  79170. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79171. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79172. * @returns a Float32Array containing matrices data
  79173. */
  79174. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79175. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79176. return mesh._bonesTransformMatrices;
  79177. }
  79178. if (!this._transformMatrices) {
  79179. this.prepare();
  79180. }
  79181. return this._transformMatrices;
  79182. };
  79183. /**
  79184. * Gets the current hosting scene
  79185. * @returns a scene object
  79186. */
  79187. Skeleton.prototype.getScene = function () {
  79188. return this._scene;
  79189. };
  79190. // Methods
  79191. /**
  79192. * Gets a string representing the current skeleton data
  79193. * @param fullDetails defines a boolean indicating if we want a verbose version
  79194. * @returns a string representing the current skeleton data
  79195. */
  79196. Skeleton.prototype.toString = function (fullDetails) {
  79197. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79198. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79199. if (fullDetails) {
  79200. ret += ", Ranges: {";
  79201. var first = true;
  79202. for (var name_1 in this._ranges) {
  79203. if (first) {
  79204. ret += ", ";
  79205. first = false;
  79206. }
  79207. ret += name_1;
  79208. }
  79209. ret += "}";
  79210. }
  79211. return ret;
  79212. };
  79213. /**
  79214. * Get bone's index searching by name
  79215. * @param name defines bone's name to search for
  79216. * @return the indice of the bone. Returns -1 if not found
  79217. */
  79218. Skeleton.prototype.getBoneIndexByName = function (name) {
  79219. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79220. if (this.bones[boneIndex].name === name) {
  79221. return boneIndex;
  79222. }
  79223. }
  79224. return -1;
  79225. };
  79226. /**
  79227. * Creater a new animation range
  79228. * @param name defines the name of the range
  79229. * @param from defines the start key
  79230. * @param to defines the end key
  79231. */
  79232. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79233. // check name not already in use
  79234. if (!this._ranges[name]) {
  79235. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79236. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79237. if (this.bones[i].animations[0]) {
  79238. this.bones[i].animations[0].createRange(name, from, to);
  79239. }
  79240. }
  79241. }
  79242. };
  79243. /**
  79244. * Delete a specific animation range
  79245. * @param name defines the name of the range
  79246. * @param deleteFrames defines if frames must be removed as well
  79247. */
  79248. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79249. if (deleteFrames === void 0) { deleteFrames = true; }
  79250. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79251. if (this.bones[i].animations[0]) {
  79252. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79253. }
  79254. }
  79255. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79256. };
  79257. /**
  79258. * Gets a specific animation range
  79259. * @param name defines the name of the range to look for
  79260. * @returns the requested animation range or null if not found
  79261. */
  79262. Skeleton.prototype.getAnimationRange = function (name) {
  79263. return this._ranges[name];
  79264. };
  79265. /**
  79266. * Gets the list of all animation ranges defined on this skeleton
  79267. * @returns an array
  79268. */
  79269. Skeleton.prototype.getAnimationRanges = function () {
  79270. var animationRanges = [];
  79271. var name;
  79272. var i = 0;
  79273. for (name in this._ranges) {
  79274. animationRanges[i] = this._ranges[name];
  79275. i++;
  79276. }
  79277. return animationRanges;
  79278. };
  79279. /**
  79280. * Copy animation range from a source skeleton.
  79281. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79282. * @param source defines the source skeleton
  79283. * @param name defines the name of the range to copy
  79284. * @param rescaleAsRequired defines if rescaling must be applied if required
  79285. * @returns true if operation was successful
  79286. */
  79287. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79288. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79289. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79290. return false;
  79291. }
  79292. var ret = true;
  79293. var frameOffset = this._getHighestAnimationFrame() + 1;
  79294. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79295. var boneDict = {};
  79296. var sourceBones = source.bones;
  79297. var nBones;
  79298. var i;
  79299. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79300. boneDict[sourceBones[i].name] = sourceBones[i];
  79301. }
  79302. if (this.bones.length !== sourceBones.length) {
  79303. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79304. ret = false;
  79305. }
  79306. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79307. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79308. var boneName = this.bones[i].name;
  79309. var sourceBone = boneDict[boneName];
  79310. if (sourceBone) {
  79311. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79312. }
  79313. else {
  79314. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79315. ret = false;
  79316. }
  79317. }
  79318. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79319. var range = source.getAnimationRange(name);
  79320. if (range) {
  79321. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79322. }
  79323. return ret;
  79324. };
  79325. /**
  79326. * Forces the skeleton to go to rest pose
  79327. */
  79328. Skeleton.prototype.returnToRest = function () {
  79329. for (var index = 0; index < this.bones.length; index++) {
  79330. this.bones[index].returnToRest();
  79331. }
  79332. };
  79333. Skeleton.prototype._getHighestAnimationFrame = function () {
  79334. var ret = 0;
  79335. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79336. if (this.bones[i].animations[0]) {
  79337. var highest = this.bones[i].animations[0].getHighestFrame();
  79338. if (ret < highest) {
  79339. ret = highest;
  79340. }
  79341. }
  79342. }
  79343. return ret;
  79344. };
  79345. /**
  79346. * Begin a specific animation range
  79347. * @param name defines the name of the range to start
  79348. * @param loop defines if looping must be turned on (false by default)
  79349. * @param speedRatio defines the speed ratio to apply (1 by default)
  79350. * @param onAnimationEnd defines a callback which will be called when animation will end
  79351. * @returns a new animatable
  79352. */
  79353. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79354. var range = this.getAnimationRange(name);
  79355. if (!range) {
  79356. return null;
  79357. }
  79358. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79359. };
  79360. /** @hidden */
  79361. Skeleton.prototype._markAsDirty = function () {
  79362. this._isDirty = true;
  79363. };
  79364. /** @hidden */
  79365. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79366. this._meshesWithPoseMatrix.push(mesh);
  79367. };
  79368. /** @hidden */
  79369. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79370. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79371. if (index > -1) {
  79372. this._meshesWithPoseMatrix.splice(index, 1);
  79373. }
  79374. };
  79375. /** @hidden */
  79376. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79377. this.onBeforeComputeObservable.notifyObservers(this);
  79378. for (var index = 0; index < this.bones.length; index++) {
  79379. var bone = this.bones[index];
  79380. var parentBone = bone.getParent();
  79381. if (parentBone) {
  79382. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79383. }
  79384. else {
  79385. if (initialSkinMatrix) {
  79386. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79387. }
  79388. else {
  79389. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79390. }
  79391. }
  79392. if (bone._index !== -1) {
  79393. var mappedIndex = bone._index === null ? index : bone._index;
  79394. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79395. }
  79396. }
  79397. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79398. };
  79399. /**
  79400. * Build all resources required to render a skeleton
  79401. */
  79402. Skeleton.prototype.prepare = function () {
  79403. if (!this._isDirty) {
  79404. return;
  79405. }
  79406. if (this.needInitialSkinMatrix) {
  79407. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79408. var mesh = this._meshesWithPoseMatrix[index];
  79409. var poseMatrix = mesh.getPoseMatrix();
  79410. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79411. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79412. }
  79413. if (this._synchronizedWithMesh !== mesh) {
  79414. this._synchronizedWithMesh = mesh;
  79415. // Prepare bones
  79416. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79417. var bone = this.bones[boneIndex];
  79418. if (!bone.getParent()) {
  79419. var matrix = bone.getBaseMatrix();
  79420. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79421. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79422. }
  79423. }
  79424. }
  79425. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79426. }
  79427. }
  79428. else {
  79429. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79430. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79431. }
  79432. this._computeTransformMatrices(this._transformMatrices, null);
  79433. }
  79434. this._isDirty = false;
  79435. this._scene._activeBones.addCount(this.bones.length, false);
  79436. };
  79437. /**
  79438. * Gets the list of animatables currently running for this skeleton
  79439. * @returns an array of animatables
  79440. */
  79441. Skeleton.prototype.getAnimatables = function () {
  79442. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79443. this._animatables = [];
  79444. for (var index = 0; index < this.bones.length; index++) {
  79445. this._animatables.push(this.bones[index]);
  79446. }
  79447. }
  79448. return this._animatables;
  79449. };
  79450. /**
  79451. * Clone the current skeleton
  79452. * @param name defines the name of the new skeleton
  79453. * @param id defines the id of the enw skeleton
  79454. * @returns the new skeleton
  79455. */
  79456. Skeleton.prototype.clone = function (name, id) {
  79457. var result = new Skeleton(name, id || name, this._scene);
  79458. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79459. for (var index = 0; index < this.bones.length; index++) {
  79460. var source = this.bones[index];
  79461. var parentBone = null;
  79462. var parent_1 = source.getParent();
  79463. if (parent_1) {
  79464. var parentIndex = this.bones.indexOf(parent_1);
  79465. parentBone = result.bones[parentIndex];
  79466. }
  79467. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79468. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79469. }
  79470. if (this._ranges) {
  79471. result._ranges = {};
  79472. for (var rangeName in this._ranges) {
  79473. var range = this._ranges[rangeName];
  79474. if (range) {
  79475. result._ranges[rangeName] = range.clone();
  79476. }
  79477. }
  79478. }
  79479. this._isDirty = true;
  79480. return result;
  79481. };
  79482. /**
  79483. * Enable animation blending for this skeleton
  79484. * @param blendingSpeed defines the blending speed to apply
  79485. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79486. */
  79487. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79488. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79489. this.bones.forEach(function (bone) {
  79490. bone.animations.forEach(function (animation) {
  79491. animation.enableBlending = true;
  79492. animation.blendingSpeed = blendingSpeed;
  79493. });
  79494. });
  79495. };
  79496. /**
  79497. * Releases all resources associated with the current skeleton
  79498. */
  79499. Skeleton.prototype.dispose = function () {
  79500. this._meshesWithPoseMatrix = [];
  79501. // Animations
  79502. this.getScene().stopAnimation(this);
  79503. // Remove from scene
  79504. this.getScene().removeSkeleton(this);
  79505. };
  79506. /**
  79507. * Serialize the skeleton in a JSON object
  79508. * @returns a JSON object
  79509. */
  79510. Skeleton.prototype.serialize = function () {
  79511. var serializationObject = {};
  79512. serializationObject.name = this.name;
  79513. serializationObject.id = this.id;
  79514. if (this.dimensionsAtRest) {
  79515. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  79516. }
  79517. serializationObject.bones = [];
  79518. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79519. for (var index = 0; index < this.bones.length; index++) {
  79520. var bone = this.bones[index];
  79521. var parent_2 = bone.getParent();
  79522. var serializedBone = {
  79523. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  79524. name: bone.name,
  79525. matrix: bone.getBaseMatrix().toArray(),
  79526. rest: bone.getRestPose().toArray()
  79527. };
  79528. serializationObject.bones.push(serializedBone);
  79529. if (bone.length) {
  79530. serializedBone.length = bone.length;
  79531. }
  79532. if (bone.metadata) {
  79533. serializedBone.metadata = bone.metadata;
  79534. }
  79535. if (bone.animations && bone.animations.length > 0) {
  79536. serializedBone.animation = bone.animations[0].serialize();
  79537. }
  79538. serializationObject.ranges = [];
  79539. for (var name in this._ranges) {
  79540. var source = this._ranges[name];
  79541. if (!source) {
  79542. continue;
  79543. }
  79544. var range = {};
  79545. range.name = name;
  79546. range.from = source.from;
  79547. range.to = source.to;
  79548. serializationObject.ranges.push(range);
  79549. }
  79550. }
  79551. return serializationObject;
  79552. };
  79553. /**
  79554. * Creates a new skeleton from serialized data
  79555. * @param parsedSkeleton defines the serialized data
  79556. * @param scene defines the hosting scene
  79557. * @returns a new skeleton
  79558. */
  79559. Skeleton.Parse = function (parsedSkeleton, scene) {
  79560. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  79561. if (parsedSkeleton.dimensionsAtRest) {
  79562. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  79563. }
  79564. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  79565. var index;
  79566. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  79567. var parsedBone = parsedSkeleton.bones[index];
  79568. var parentBone = null;
  79569. if (parsedBone.parentBoneIndex > -1) {
  79570. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  79571. }
  79572. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  79573. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  79574. if (parsedBone.length) {
  79575. bone.length = parsedBone.length;
  79576. }
  79577. if (parsedBone.metadata) {
  79578. bone.metadata = parsedBone.metadata;
  79579. }
  79580. if (parsedBone.animation) {
  79581. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  79582. }
  79583. }
  79584. // placed after bones, so createAnimationRange can cascade down
  79585. if (parsedSkeleton.ranges) {
  79586. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  79587. var data = parsedSkeleton.ranges[index];
  79588. skeleton.createAnimationRange(data.name, data.from, data.to);
  79589. }
  79590. }
  79591. return skeleton;
  79592. };
  79593. /**
  79594. * Compute all node absolute transforms
  79595. * @param forceUpdate defines if computation must be done even if cache is up to date
  79596. */
  79597. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  79598. if (forceUpdate === void 0) { forceUpdate = false; }
  79599. var renderId = this._scene.getRenderId();
  79600. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  79601. this.bones[0].computeAbsoluteTransforms();
  79602. this._lastAbsoluteTransformsUpdateId = renderId;
  79603. }
  79604. };
  79605. /**
  79606. * Gets the root pose matrix
  79607. * @returns a matrix
  79608. */
  79609. Skeleton.prototype.getPoseMatrix = function () {
  79610. var poseMatrix = null;
  79611. if (this._meshesWithPoseMatrix.length > 0) {
  79612. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  79613. }
  79614. return poseMatrix;
  79615. };
  79616. /**
  79617. * Sorts bones per internal index
  79618. */
  79619. Skeleton.prototype.sortBones = function () {
  79620. var bones = new Array();
  79621. var visited = new Array(this.bones.length);
  79622. for (var index = 0; index < this.bones.length; index++) {
  79623. this._sortBones(index, bones, visited);
  79624. }
  79625. this.bones = bones;
  79626. };
  79627. Skeleton.prototype._sortBones = function (index, bones, visited) {
  79628. if (visited[index]) {
  79629. return;
  79630. }
  79631. visited[index] = true;
  79632. var bone = this.bones[index];
  79633. if (bone._index === undefined) {
  79634. bone._index = index;
  79635. }
  79636. var parentBone = bone.getParent();
  79637. if (parentBone) {
  79638. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  79639. }
  79640. bones.push(bone);
  79641. };
  79642. return Skeleton;
  79643. }());
  79644. BABYLON.Skeleton = Skeleton;
  79645. })(BABYLON || (BABYLON = {}));
  79646. //# sourceMappingURL=babylon.skeleton.js.map
  79647. var BABYLON;
  79648. (function (BABYLON) {
  79649. var SphericalPolynomial = /** @class */ (function () {
  79650. function SphericalPolynomial() {
  79651. this.x = BABYLON.Vector3.Zero();
  79652. this.y = BABYLON.Vector3.Zero();
  79653. this.z = BABYLON.Vector3.Zero();
  79654. this.xx = BABYLON.Vector3.Zero();
  79655. this.yy = BABYLON.Vector3.Zero();
  79656. this.zz = BABYLON.Vector3.Zero();
  79657. this.xy = BABYLON.Vector3.Zero();
  79658. this.yz = BABYLON.Vector3.Zero();
  79659. this.zx = BABYLON.Vector3.Zero();
  79660. }
  79661. SphericalPolynomial.prototype.addAmbient = function (color) {
  79662. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79663. this.xx = this.xx.add(colorVector);
  79664. this.yy = this.yy.add(colorVector);
  79665. this.zz = this.zz.add(colorVector);
  79666. };
  79667. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  79668. var result = new SphericalPolynomial();
  79669. result.x = harmonics.L11.scale(1.02333);
  79670. result.y = harmonics.L1_1.scale(1.02333);
  79671. result.z = harmonics.L10.scale(1.02333);
  79672. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  79673. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  79674. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  79675. result.yz = harmonics.L2_1.scale(0.858086);
  79676. result.zx = harmonics.L21.scale(0.858086);
  79677. result.xy = harmonics.L2_2.scale(0.858086);
  79678. result.scale(1.0 / Math.PI);
  79679. return result;
  79680. };
  79681. SphericalPolynomial.prototype.scale = function (scale) {
  79682. this.x = this.x.scale(scale);
  79683. this.y = this.y.scale(scale);
  79684. this.z = this.z.scale(scale);
  79685. this.xx = this.xx.scale(scale);
  79686. this.yy = this.yy.scale(scale);
  79687. this.zz = this.zz.scale(scale);
  79688. this.yz = this.yz.scale(scale);
  79689. this.zx = this.zx.scale(scale);
  79690. this.xy = this.xy.scale(scale);
  79691. };
  79692. return SphericalPolynomial;
  79693. }());
  79694. BABYLON.SphericalPolynomial = SphericalPolynomial;
  79695. var SphericalHarmonics = /** @class */ (function () {
  79696. function SphericalHarmonics() {
  79697. this.L00 = BABYLON.Vector3.Zero();
  79698. this.L1_1 = BABYLON.Vector3.Zero();
  79699. this.L10 = BABYLON.Vector3.Zero();
  79700. this.L11 = BABYLON.Vector3.Zero();
  79701. this.L2_2 = BABYLON.Vector3.Zero();
  79702. this.L2_1 = BABYLON.Vector3.Zero();
  79703. this.L20 = BABYLON.Vector3.Zero();
  79704. this.L21 = BABYLON.Vector3.Zero();
  79705. this.L22 = BABYLON.Vector3.Zero();
  79706. }
  79707. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  79708. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79709. var c = colorVector.scale(deltaSolidAngle);
  79710. this.L00 = this.L00.add(c.scale(0.282095));
  79711. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  79712. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  79713. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  79714. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  79715. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  79716. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  79717. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  79718. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  79719. };
  79720. SphericalHarmonics.prototype.scale = function (scale) {
  79721. this.L00 = this.L00.scale(scale);
  79722. this.L1_1 = this.L1_1.scale(scale);
  79723. this.L10 = this.L10.scale(scale);
  79724. this.L11 = this.L11.scale(scale);
  79725. this.L2_2 = this.L2_2.scale(scale);
  79726. this.L2_1 = this.L2_1.scale(scale);
  79727. this.L20 = this.L20.scale(scale);
  79728. this.L21 = this.L21.scale(scale);
  79729. this.L22 = this.L22.scale(scale);
  79730. };
  79731. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  79732. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  79733. //
  79734. // E_lm = A_l * L_lm
  79735. //
  79736. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  79737. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  79738. // the scaling factors are given in equation 9.
  79739. // Constant (Band 0)
  79740. this.L00 = this.L00.scale(3.141593);
  79741. // Linear (Band 1)
  79742. this.L1_1 = this.L1_1.scale(2.094395);
  79743. this.L10 = this.L10.scale(2.094395);
  79744. this.L11 = this.L11.scale(2.094395);
  79745. // Quadratic (Band 2)
  79746. this.L2_2 = this.L2_2.scale(0.785398);
  79747. this.L2_1 = this.L2_1.scale(0.785398);
  79748. this.L20 = this.L20.scale(0.785398);
  79749. this.L21 = this.L21.scale(0.785398);
  79750. this.L22 = this.L22.scale(0.785398);
  79751. };
  79752. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  79753. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  79754. // L = (1/pi) * E * rho
  79755. //
  79756. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  79757. this.scale(1.0 / Math.PI);
  79758. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  79759. // (The pixel shader must apply albedo after texture fetches, etc).
  79760. };
  79761. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  79762. var result = new SphericalHarmonics();
  79763. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  79764. result.L1_1 = polynomial.y.scale(0.977204);
  79765. result.L10 = polynomial.z.scale(0.977204);
  79766. result.L11 = polynomial.x.scale(0.977204);
  79767. result.L2_2 = polynomial.xy.scale(1.16538);
  79768. result.L2_1 = polynomial.yz.scale(1.16538);
  79769. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79770. result.L21 = polynomial.zx.scale(1.16538);
  79771. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79772. result.scale(Math.PI);
  79773. return result;
  79774. };
  79775. return SphericalHarmonics;
  79776. }());
  79777. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79778. })(BABYLON || (BABYLON = {}));
  79779. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79780. var BABYLON;
  79781. (function (BABYLON) {
  79782. var FileFaceOrientation = /** @class */ (function () {
  79783. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  79784. this.name = name;
  79785. this.worldAxisForNormal = worldAxisForNormal;
  79786. this.worldAxisForFileX = worldAxisForFileX;
  79787. this.worldAxisForFileY = worldAxisForFileY;
  79788. }
  79789. return FileFaceOrientation;
  79790. }());
  79791. ;
  79792. /**
  79793. * Helper class dealing with the extraction of spherical polynomial dataArray
  79794. * from a cube map.
  79795. */
  79796. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  79797. function CubeMapToSphericalPolynomialTools() {
  79798. }
  79799. /**
  79800. * Converts a texture to the according Spherical Polynomial data.
  79801. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79802. *
  79803. * @param texture The texture to extract the information from.
  79804. * @return The Spherical Polynomial data.
  79805. */
  79806. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  79807. if (!texture.isCube) {
  79808. // Only supports cube Textures currently.
  79809. return null;
  79810. }
  79811. var size = texture.getSize().width;
  79812. var right = texture.readPixels(0);
  79813. var left = texture.readPixels(1);
  79814. var up;
  79815. var down;
  79816. if (texture.isRenderTarget) {
  79817. up = texture.readPixels(3);
  79818. down = texture.readPixels(2);
  79819. }
  79820. else {
  79821. up = texture.readPixels(2);
  79822. down = texture.readPixels(3);
  79823. }
  79824. var front = texture.readPixels(4);
  79825. var back = texture.readPixels(5);
  79826. var gammaSpace = texture.gammaSpace;
  79827. // Always read as RGBA.
  79828. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  79829. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79830. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79831. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79832. }
  79833. var cubeInfo = {
  79834. size: size,
  79835. right: right,
  79836. left: left,
  79837. up: up,
  79838. down: down,
  79839. front: front,
  79840. back: back,
  79841. format: format,
  79842. type: type,
  79843. gammaSpace: gammaSpace,
  79844. };
  79845. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  79846. };
  79847. /**
  79848. * Converts a cubemap to the according Spherical Polynomial data.
  79849. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79850. *
  79851. * @param cubeInfo The Cube map to extract the information from.
  79852. * @return The Spherical Polynomial data.
  79853. */
  79854. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  79855. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  79856. var totalSolidAngle = 0.0;
  79857. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  79858. var du = 2.0 / cubeInfo.size;
  79859. var dv = du;
  79860. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  79861. var minUV = du * 0.5 - 1.0;
  79862. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79863. var fileFace = this.FileFaces[faceIndex];
  79864. var dataArray = cubeInfo[fileFace.name];
  79865. var v = minUV;
  79866. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  79867. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  79868. // Because SP is still linear, so summation is fine in that basis.
  79869. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  79870. for (var y = 0; y < cubeInfo.size; y++) {
  79871. var u = minUV;
  79872. for (var x = 0; x < cubeInfo.size; x++) {
  79873. // World direction (not normalised)
  79874. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  79875. worldDirection.normalize();
  79876. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  79877. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  79878. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  79879. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  79880. // Handle Integer types.
  79881. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79882. r /= 255;
  79883. g /= 255;
  79884. b /= 255;
  79885. }
  79886. // Handle Gamma space textures.
  79887. if (cubeInfo.gammaSpace) {
  79888. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  79889. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  79890. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  79891. }
  79892. var color = new BABYLON.Color3(r, g, b);
  79893. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  79894. totalSolidAngle += deltaSolidAngle;
  79895. u += du;
  79896. }
  79897. v += dv;
  79898. }
  79899. }
  79900. // Solid angle for entire sphere is 4*pi
  79901. var sphereSolidAngle = 4.0 * Math.PI;
  79902. // Adjust the solid angle to allow for how many faces we processed.
  79903. var facesProcessed = 6.0;
  79904. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  79905. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  79906. // This is needed because the numerical integration over the cube uses a
  79907. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  79908. // and also to compensate for accumulative error due to float precision in the summation.
  79909. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  79910. sphericalHarmonics.scale(correctionFactor);
  79911. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  79912. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  79913. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  79914. };
  79915. CubeMapToSphericalPolynomialTools.FileFaces = [
  79916. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  79917. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  79918. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  79919. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  79920. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  79921. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  79922. ];
  79923. return CubeMapToSphericalPolynomialTools;
  79924. }());
  79925. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  79926. })(BABYLON || (BABYLON = {}));
  79927. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  79928. var BABYLON;
  79929. (function (BABYLON) {
  79930. /**
  79931. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  79932. */
  79933. var PanoramaToCubeMapTools = /** @class */ (function () {
  79934. function PanoramaToCubeMapTools() {
  79935. }
  79936. /**
  79937. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  79938. *
  79939. * @param float32Array The source data.
  79940. * @param inputWidth The width of the input panorama.
  79941. * @param inputhHeight The height of the input panorama.
  79942. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  79943. * @return The cubemap data
  79944. */
  79945. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  79946. if (!float32Array) {
  79947. throw "ConvertPanoramaToCubemap: input cannot be null";
  79948. }
  79949. if (float32Array.length != inputWidth * inputHeight * 3) {
  79950. throw "ConvertPanoramaToCubemap: input size is wrong";
  79951. }
  79952. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  79953. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  79954. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  79955. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  79956. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  79957. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  79958. return {
  79959. front: textureFront,
  79960. back: textureBack,
  79961. left: textureLeft,
  79962. right: textureRight,
  79963. up: textureUp,
  79964. down: textureDown,
  79965. size: size,
  79966. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  79967. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  79968. gammaSpace: false,
  79969. };
  79970. };
  79971. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  79972. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  79973. var textureArray = new Float32Array(buffer);
  79974. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  79975. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  79976. var dy = 1 / texSize;
  79977. var fy = 0;
  79978. for (var y = 0; y < texSize; y++) {
  79979. var xv1 = faceData[0];
  79980. var xv2 = faceData[2];
  79981. for (var x = 0; x < texSize; x++) {
  79982. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  79983. v.normalize();
  79984. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  79985. // 3 channels per pixels
  79986. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  79987. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  79988. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  79989. xv1 = xv1.add(rotDX1);
  79990. xv2 = xv2.add(rotDX2);
  79991. }
  79992. fy += dy;
  79993. }
  79994. return textureArray;
  79995. };
  79996. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  79997. var theta = Math.atan2(vDir.z, vDir.x);
  79998. var phi = Math.acos(vDir.y);
  79999. while (theta < -Math.PI)
  80000. theta += 2 * Math.PI;
  80001. while (theta > Math.PI)
  80002. theta -= 2 * Math.PI;
  80003. var dx = theta / Math.PI;
  80004. var dy = phi / Math.PI;
  80005. // recenter.
  80006. dx = dx * 0.5 + 0.5;
  80007. var px = Math.round(dx * inputWidth);
  80008. if (px < 0)
  80009. px = 0;
  80010. else if (px >= inputWidth)
  80011. px = inputWidth - 1;
  80012. var py = Math.round(dy * inputHeight);
  80013. if (py < 0)
  80014. py = 0;
  80015. else if (py >= inputHeight)
  80016. py = inputHeight - 1;
  80017. var inputY = (inputHeight - py - 1);
  80018. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80019. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80020. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80021. return {
  80022. r: r,
  80023. g: g,
  80024. b: b
  80025. };
  80026. };
  80027. PanoramaToCubeMapTools.FACE_FRONT = [
  80028. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80029. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80030. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80031. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80032. ];
  80033. PanoramaToCubeMapTools.FACE_BACK = [
  80034. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80035. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80036. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80037. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80038. ];
  80039. PanoramaToCubeMapTools.FACE_RIGHT = [
  80040. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80041. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80042. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80043. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80044. ];
  80045. PanoramaToCubeMapTools.FACE_LEFT = [
  80046. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80047. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80048. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80049. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80050. ];
  80051. PanoramaToCubeMapTools.FACE_DOWN = [
  80052. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80053. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80054. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80055. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80056. ];
  80057. PanoramaToCubeMapTools.FACE_UP = [
  80058. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80059. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80060. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80061. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80062. ];
  80063. return PanoramaToCubeMapTools;
  80064. }());
  80065. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80066. })(BABYLON || (BABYLON = {}));
  80067. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80068. var BABYLON;
  80069. (function (BABYLON) {
  80070. ;
  80071. /**
  80072. * This groups tools to convert HDR texture to native colors array.
  80073. */
  80074. var HDRTools = /** @class */ (function () {
  80075. function HDRTools() {
  80076. }
  80077. HDRTools.Ldexp = function (mantissa, exponent) {
  80078. if (exponent > 1023) {
  80079. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80080. }
  80081. if (exponent < -1074) {
  80082. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80083. }
  80084. return mantissa * Math.pow(2, exponent);
  80085. };
  80086. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80087. if (exponent > 0) { /*nonzero pixel*/
  80088. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80089. float32array[index + 0] = red * exponent;
  80090. float32array[index + 1] = green * exponent;
  80091. float32array[index + 2] = blue * exponent;
  80092. }
  80093. else {
  80094. float32array[index + 0] = 0;
  80095. float32array[index + 1] = 0;
  80096. float32array[index + 2] = 0;
  80097. }
  80098. };
  80099. HDRTools.readStringLine = function (uint8array, startIndex) {
  80100. var line = "";
  80101. var character = "";
  80102. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80103. character = String.fromCharCode(uint8array[i]);
  80104. if (character == "\n") {
  80105. break;
  80106. }
  80107. line += character;
  80108. }
  80109. return line;
  80110. };
  80111. /**
  80112. * Reads header information from an RGBE texture stored in a native array.
  80113. * More information on this format are available here:
  80114. * https://en.wikipedia.org/wiki/RGBE_image_format
  80115. *
  80116. * @param uint8array The binary file stored in native array.
  80117. * @return The header information.
  80118. */
  80119. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80120. var height = 0;
  80121. var width = 0;
  80122. var line = this.readStringLine(uint8array, 0);
  80123. if (line[0] != '#' || line[1] != '?') {
  80124. throw "Bad HDR Format.";
  80125. }
  80126. var endOfHeader = false;
  80127. var findFormat = false;
  80128. var lineIndex = 0;
  80129. do {
  80130. lineIndex += (line.length + 1);
  80131. line = this.readStringLine(uint8array, lineIndex);
  80132. if (line == "FORMAT=32-bit_rle_rgbe") {
  80133. findFormat = true;
  80134. }
  80135. else if (line.length == 0) {
  80136. endOfHeader = true;
  80137. }
  80138. } while (!endOfHeader);
  80139. if (!findFormat) {
  80140. throw "HDR Bad header format, unsupported FORMAT";
  80141. }
  80142. lineIndex += (line.length + 1);
  80143. line = this.readStringLine(uint8array, lineIndex);
  80144. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80145. var match = sizeRegexp.exec(line);
  80146. // TODO. Support +Y and -X if needed.
  80147. if (!match || match.length < 3) {
  80148. throw "HDR Bad header format, no size";
  80149. }
  80150. width = parseInt(match[2]);
  80151. height = parseInt(match[1]);
  80152. if (width < 8 || width > 0x7fff) {
  80153. throw "HDR Bad header format, unsupported size";
  80154. }
  80155. lineIndex += (line.length + 1);
  80156. return {
  80157. height: height,
  80158. width: width,
  80159. dataPosition: lineIndex
  80160. };
  80161. };
  80162. /**
  80163. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80164. * This RGBE texture needs to store the information as a panorama.
  80165. *
  80166. * More information on this format are available here:
  80167. * https://en.wikipedia.org/wiki/RGBE_image_format
  80168. *
  80169. * @param buffer The binary file stored in an array buffer.
  80170. * @param size The expected size of the extracted cubemap.
  80171. * @return The Cube Map information.
  80172. */
  80173. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80174. var uint8array = new Uint8Array(buffer);
  80175. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80176. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80177. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80178. return cubeMapData;
  80179. };
  80180. /**
  80181. * Returns the pixels data extracted from an RGBE texture.
  80182. * This pixels will be stored left to right up to down in the R G B order in one array.
  80183. *
  80184. * More information on this format are available here:
  80185. * https://en.wikipedia.org/wiki/RGBE_image_format
  80186. *
  80187. * @param uint8array The binary file stored in an array buffer.
  80188. * @param hdrInfo The header information of the file.
  80189. * @return The pixels data in RGB right to left up to down order.
  80190. */
  80191. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80192. // Keep for multi format supports.
  80193. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80194. };
  80195. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80196. var num_scanlines = hdrInfo.height;
  80197. var scanline_width = hdrInfo.width;
  80198. var a, b, c, d, count;
  80199. var dataIndex = hdrInfo.dataPosition;
  80200. var index = 0, endIndex = 0, i = 0;
  80201. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80202. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80203. // 3 channels of 4 bytes per pixel in float.
  80204. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80205. var resultArray = new Float32Array(resultBuffer);
  80206. // read in each successive scanline
  80207. while (num_scanlines > 0) {
  80208. a = uint8array[dataIndex++];
  80209. b = uint8array[dataIndex++];
  80210. c = uint8array[dataIndex++];
  80211. d = uint8array[dataIndex++];
  80212. if (a != 2 || b != 2 || (c & 0x80)) {
  80213. // this file is not run length encoded
  80214. throw "HDR Bad header format, not RLE";
  80215. }
  80216. if (((c << 8) | d) != scanline_width) {
  80217. throw "HDR Bad header format, wrong scan line width";
  80218. }
  80219. index = 0;
  80220. // read each of the four channels for the scanline into the buffer
  80221. for (i = 0; i < 4; i++) {
  80222. endIndex = (i + 1) * scanline_width;
  80223. while (index < endIndex) {
  80224. a = uint8array[dataIndex++];
  80225. b = uint8array[dataIndex++];
  80226. if (a > 128) {
  80227. // a run of the same value
  80228. count = a - 128;
  80229. if ((count == 0) || (count > endIndex - index)) {
  80230. throw "HDR Bad Format, bad scanline data (run)";
  80231. }
  80232. while (count-- > 0) {
  80233. scanLineArray[index++] = b;
  80234. }
  80235. }
  80236. else {
  80237. // a non-run
  80238. count = a;
  80239. if ((count == 0) || (count > endIndex - index)) {
  80240. throw "HDR Bad Format, bad scanline data (non-run)";
  80241. }
  80242. scanLineArray[index++] = b;
  80243. if (--count > 0) {
  80244. for (var j = 0; j < count; j++) {
  80245. scanLineArray[index++] = uint8array[dataIndex++];
  80246. }
  80247. }
  80248. }
  80249. }
  80250. }
  80251. // now convert data from buffer into floats
  80252. for (i = 0; i < scanline_width; i++) {
  80253. a = scanLineArray[i];
  80254. b = scanLineArray[i + scanline_width];
  80255. c = scanLineArray[i + 2 * scanline_width];
  80256. d = scanLineArray[i + 3 * scanline_width];
  80257. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80258. }
  80259. num_scanlines--;
  80260. }
  80261. return resultArray;
  80262. };
  80263. return HDRTools;
  80264. }());
  80265. BABYLON.HDRTools = HDRTools;
  80266. })(BABYLON || (BABYLON = {}));
  80267. //# sourceMappingURL=babylon.hdr.js.map
  80268. var BABYLON;
  80269. (function (BABYLON) {
  80270. /**
  80271. * This represents a texture coming from an HDR input.
  80272. *
  80273. * The only supported format is currently panorama picture stored in RGBE format.
  80274. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80275. */
  80276. var HDRCubeTexture = /** @class */ (function (_super) {
  80277. __extends(HDRCubeTexture, _super);
  80278. /**
  80279. * Instantiates an HDRTexture from the following parameters.
  80280. *
  80281. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80282. * @param scene The scene the texture will be used in
  80283. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80284. * @param noMipmap Forces to not generate the mipmap if true
  80285. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80286. * @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)
  80287. * @param reserved Reserved flag for internal use.
  80288. */
  80289. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80290. if (noMipmap === void 0) { noMipmap = false; }
  80291. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80292. if (gammaSpace === void 0) { gammaSpace = false; }
  80293. if (reserved === void 0) { reserved = false; }
  80294. if (onLoad === void 0) { onLoad = null; }
  80295. if (onError === void 0) { onError = null; }
  80296. var _this = _super.call(this, scene) || this;
  80297. _this._generateHarmonics = true;
  80298. _this._onLoad = null;
  80299. _this._onError = null;
  80300. /**
  80301. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80302. */
  80303. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80304. _this._isBlocking = true;
  80305. _this._rotationY = 0;
  80306. /**
  80307. * Gets or sets the center of the bounding box associated with the cube texture
  80308. * It must define where the camera used to render the texture was set
  80309. */
  80310. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80311. if (!url) {
  80312. return _this;
  80313. }
  80314. _this.name = url;
  80315. _this.url = url;
  80316. _this.hasAlpha = false;
  80317. _this.isCube = true;
  80318. _this._textureMatrix = BABYLON.Matrix.Identity();
  80319. _this._onLoad = onLoad;
  80320. _this._onError = onError;
  80321. _this.gammaSpace = gammaSpace;
  80322. _this._noMipmap = noMipmap;
  80323. _this._size = size;
  80324. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80325. if (!_this._texture) {
  80326. if (!scene.useDelayedTextureLoading) {
  80327. _this.loadTexture();
  80328. }
  80329. else {
  80330. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80331. }
  80332. }
  80333. return _this;
  80334. }
  80335. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80336. /**
  80337. * Gets wether or not the texture is blocking during loading.
  80338. */
  80339. get: function () {
  80340. return this._isBlocking;
  80341. },
  80342. /**
  80343. * Sets wether or not the texture is blocking during loading.
  80344. */
  80345. set: function (value) {
  80346. this._isBlocking = value;
  80347. },
  80348. enumerable: true,
  80349. configurable: true
  80350. });
  80351. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80352. /**
  80353. * Gets texture matrix rotation angle around Y axis radians.
  80354. */
  80355. get: function () {
  80356. return this._rotationY;
  80357. },
  80358. /**
  80359. * Sets texture matrix rotation angle around Y axis in radians.
  80360. */
  80361. set: function (value) {
  80362. this._rotationY = value;
  80363. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80364. },
  80365. enumerable: true,
  80366. configurable: true
  80367. });
  80368. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80369. get: function () {
  80370. return this._boundingBoxSize;
  80371. },
  80372. /**
  80373. * Gets or sets the size of the bounding box associated with the cube texture
  80374. * When defined, the cubemap will switch to local mode
  80375. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80376. * @example https://www.babylonjs-playground.com/#RNASML
  80377. */
  80378. set: function (value) {
  80379. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80380. return;
  80381. }
  80382. this._boundingBoxSize = value;
  80383. var scene = this.getScene();
  80384. if (scene) {
  80385. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80386. }
  80387. },
  80388. enumerable: true,
  80389. configurable: true
  80390. });
  80391. /**
  80392. * Occurs when the file is raw .hdr file.
  80393. */
  80394. HDRCubeTexture.prototype.loadTexture = function () {
  80395. var _this = this;
  80396. var callback = function (buffer) {
  80397. var scene = _this.getScene();
  80398. if (!scene) {
  80399. return null;
  80400. }
  80401. // Extract the raw linear data.
  80402. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80403. // Generate harmonics if needed.
  80404. if (_this._generateHarmonics) {
  80405. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80406. _this.sphericalPolynomial = sphericalPolynomial;
  80407. }
  80408. var results = [];
  80409. var byteArray = null;
  80410. // Push each faces.
  80411. for (var j = 0; j < 6; j++) {
  80412. // Create uintarray fallback.
  80413. if (!scene.getEngine().getCaps().textureFloat) {
  80414. // 3 channels of 1 bytes per pixel in bytes.
  80415. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80416. byteArray = new Uint8Array(byteBuffer);
  80417. }
  80418. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80419. // If special cases.
  80420. if (_this.gammaSpace || byteArray) {
  80421. for (var i = 0; i < _this._size * _this._size; i++) {
  80422. // Put in gamma space if requested.
  80423. if (_this.gammaSpace) {
  80424. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80425. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80426. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80427. }
  80428. // Convert to int texture for fallback.
  80429. if (byteArray) {
  80430. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80431. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80432. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80433. // May use luminance instead if the result is not accurate.
  80434. var max = Math.max(Math.max(r, g), b);
  80435. if (max > 255) {
  80436. var scale = 255 / max;
  80437. r *= scale;
  80438. g *= scale;
  80439. b *= scale;
  80440. }
  80441. byteArray[(i * 3) + 0] = r;
  80442. byteArray[(i * 3) + 1] = g;
  80443. byteArray[(i * 3) + 2] = b;
  80444. }
  80445. }
  80446. }
  80447. if (byteArray) {
  80448. results.push(byteArray);
  80449. }
  80450. else {
  80451. results.push(dataFace);
  80452. }
  80453. }
  80454. return results;
  80455. };
  80456. var scene = this.getScene();
  80457. if (scene) {
  80458. 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);
  80459. }
  80460. };
  80461. HDRCubeTexture.prototype.clone = function () {
  80462. var scene = this.getScene();
  80463. if (!scene) {
  80464. return this;
  80465. }
  80466. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  80467. // Base texture
  80468. newTexture.level = this.level;
  80469. newTexture.wrapU = this.wrapU;
  80470. newTexture.wrapV = this.wrapV;
  80471. newTexture.coordinatesIndex = this.coordinatesIndex;
  80472. newTexture.coordinatesMode = this.coordinatesMode;
  80473. return newTexture;
  80474. };
  80475. // Methods
  80476. HDRCubeTexture.prototype.delayLoad = function () {
  80477. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80478. return;
  80479. }
  80480. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80481. this._texture = this._getFromCache(this.url, this._noMipmap);
  80482. if (!this._texture) {
  80483. this.loadTexture();
  80484. }
  80485. };
  80486. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80487. return this._textureMatrix;
  80488. };
  80489. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80490. this._textureMatrix = value;
  80491. };
  80492. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80493. var texture = null;
  80494. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80495. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  80496. texture.name = parsedTexture.name;
  80497. texture.hasAlpha = parsedTexture.hasAlpha;
  80498. texture.level = parsedTexture.level;
  80499. texture.coordinatesMode = parsedTexture.coordinatesMode;
  80500. texture.isBlocking = parsedTexture.isBlocking;
  80501. }
  80502. if (texture) {
  80503. if (parsedTexture.boundingBoxPosition) {
  80504. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  80505. }
  80506. if (parsedTexture.boundingBoxSize) {
  80507. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  80508. }
  80509. if (parsedTexture.rotationY) {
  80510. texture.rotationY = parsedTexture.rotationY;
  80511. }
  80512. }
  80513. return texture;
  80514. };
  80515. HDRCubeTexture.prototype.serialize = function () {
  80516. if (!this.name) {
  80517. return null;
  80518. }
  80519. var serializationObject = {};
  80520. serializationObject.name = this.name;
  80521. serializationObject.hasAlpha = this.hasAlpha;
  80522. serializationObject.isCube = true;
  80523. serializationObject.level = this.level;
  80524. serializationObject.size = this._size;
  80525. serializationObject.coordinatesMode = this.coordinatesMode;
  80526. serializationObject.useInGammaSpace = this.gammaSpace;
  80527. serializationObject.generateHarmonics = this._generateHarmonics;
  80528. serializationObject.customType = "BABYLON.HDRCubeTexture";
  80529. serializationObject.noMipmap = this._noMipmap;
  80530. serializationObject.isBlocking = this._isBlocking;
  80531. serializationObject.rotationY = this._rotationY;
  80532. return serializationObject;
  80533. };
  80534. HDRCubeTexture._facesMapping = [
  80535. "right",
  80536. "left",
  80537. "up",
  80538. "down",
  80539. "front",
  80540. "back"
  80541. ];
  80542. return HDRCubeTexture;
  80543. }(BABYLON.BaseTexture));
  80544. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80545. })(BABYLON || (BABYLON = {}));
  80546. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80547. var BABYLON;
  80548. (function (BABYLON) {
  80549. var IndexedVector2 = /** @class */ (function (_super) {
  80550. __extends(IndexedVector2, _super);
  80551. function IndexedVector2(original, index) {
  80552. var _this = _super.call(this, original.x, original.y) || this;
  80553. _this.index = index;
  80554. return _this;
  80555. }
  80556. return IndexedVector2;
  80557. }(BABYLON.Vector2));
  80558. var PolygonPoints = /** @class */ (function () {
  80559. function PolygonPoints() {
  80560. this.elements = new Array();
  80561. }
  80562. PolygonPoints.prototype.add = function (originalPoints) {
  80563. var _this = this;
  80564. var result = new Array();
  80565. originalPoints.forEach(function (point) {
  80566. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80567. var newPoint = new IndexedVector2(point, _this.elements.length);
  80568. result.push(newPoint);
  80569. _this.elements.push(newPoint);
  80570. }
  80571. });
  80572. return result;
  80573. };
  80574. PolygonPoints.prototype.computeBounds = function () {
  80575. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80576. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80577. this.elements.forEach(function (point) {
  80578. // x
  80579. if (point.x < lmin.x) {
  80580. lmin.x = point.x;
  80581. }
  80582. else if (point.x > lmax.x) {
  80583. lmax.x = point.x;
  80584. }
  80585. // y
  80586. if (point.y < lmin.y) {
  80587. lmin.y = point.y;
  80588. }
  80589. else if (point.y > lmax.y) {
  80590. lmax.y = point.y;
  80591. }
  80592. });
  80593. return {
  80594. min: lmin,
  80595. max: lmax,
  80596. width: lmax.x - lmin.x,
  80597. height: lmax.y - lmin.y
  80598. };
  80599. };
  80600. return PolygonPoints;
  80601. }());
  80602. var Polygon = /** @class */ (function () {
  80603. function Polygon() {
  80604. }
  80605. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80606. return [
  80607. new BABYLON.Vector2(xmin, ymin),
  80608. new BABYLON.Vector2(xmax, ymin),
  80609. new BABYLON.Vector2(xmax, ymax),
  80610. new BABYLON.Vector2(xmin, ymax)
  80611. ];
  80612. };
  80613. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80614. if (cx === void 0) { cx = 0; }
  80615. if (cy === void 0) { cy = 0; }
  80616. if (numberOfSides === void 0) { numberOfSides = 32; }
  80617. var result = new Array();
  80618. var angle = 0;
  80619. var increment = (Math.PI * 2) / numberOfSides;
  80620. for (var i = 0; i < numberOfSides; i++) {
  80621. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80622. angle -= increment;
  80623. }
  80624. return result;
  80625. };
  80626. Polygon.Parse = function (input) {
  80627. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80628. var i, result = [];
  80629. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80630. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80631. }
  80632. return result;
  80633. };
  80634. Polygon.StartingAt = function (x, y) {
  80635. return BABYLON.Path2.StartingAt(x, y);
  80636. };
  80637. return Polygon;
  80638. }());
  80639. BABYLON.Polygon = Polygon;
  80640. var PolygonMeshBuilder = /** @class */ (function () {
  80641. function PolygonMeshBuilder(name, contours, scene) {
  80642. this._points = new PolygonPoints();
  80643. this._outlinepoints = new PolygonPoints();
  80644. this._holes = new Array();
  80645. this._epoints = new Array();
  80646. this._eholes = new Array();
  80647. this._name = name;
  80648. this._scene = scene;
  80649. var points;
  80650. if (contours instanceof BABYLON.Path2) {
  80651. points = contours.getPoints();
  80652. }
  80653. else {
  80654. points = contours;
  80655. }
  80656. this._addToepoint(points);
  80657. this._points.add(points);
  80658. this._outlinepoints.add(points);
  80659. if (typeof earcut === 'undefined') {
  80660. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80661. }
  80662. }
  80663. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80664. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80665. var p = points_1[_i];
  80666. this._epoints.push(p.x, p.y);
  80667. }
  80668. };
  80669. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80670. this._points.add(hole);
  80671. var holepoints = new PolygonPoints();
  80672. holepoints.add(hole);
  80673. this._holes.push(holepoints);
  80674. this._eholes.push(this._epoints.length / 2);
  80675. this._addToepoint(hole);
  80676. return this;
  80677. };
  80678. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80679. var _this = this;
  80680. if (updatable === void 0) { updatable = false; }
  80681. if (depth === void 0) { depth = 0; }
  80682. var result = new BABYLON.Mesh(this._name, this._scene);
  80683. var normals = new Array();
  80684. var positions = new Array();
  80685. var uvs = new Array();
  80686. var bounds = this._points.computeBounds();
  80687. this._points.elements.forEach(function (p) {
  80688. normals.push(0, 1.0, 0);
  80689. positions.push(p.x, 0, p.y);
  80690. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80691. });
  80692. var indices = new Array();
  80693. var res = earcut(this._epoints, this._eholes, 2);
  80694. for (var i = 0; i < res.length; i++) {
  80695. indices.push(res[i]);
  80696. }
  80697. if (depth > 0) {
  80698. var positionscount = (positions.length / 3); //get the current pointcount
  80699. this._points.elements.forEach(function (p) {
  80700. normals.push(0, -1.0, 0);
  80701. positions.push(p.x, -depth, p.y);
  80702. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80703. });
  80704. var totalCount = indices.length;
  80705. for (var i = 0; i < totalCount; i += 3) {
  80706. var i0 = indices[i + 0];
  80707. var i1 = indices[i + 1];
  80708. var i2 = indices[i + 2];
  80709. indices.push(i2 + positionscount);
  80710. indices.push(i1 + positionscount);
  80711. indices.push(i0 + positionscount);
  80712. }
  80713. //Add the sides
  80714. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80715. this._holes.forEach(function (hole) {
  80716. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80717. });
  80718. }
  80719. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80720. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80721. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80722. result.setIndices(indices);
  80723. return result;
  80724. };
  80725. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80726. var StartIndex = positions.length / 3;
  80727. var ulength = 0;
  80728. for (var i = 0; i < points.elements.length; i++) {
  80729. var p = points.elements[i];
  80730. var p1;
  80731. if ((i + 1) > points.elements.length - 1) {
  80732. p1 = points.elements[0];
  80733. }
  80734. else {
  80735. p1 = points.elements[i + 1];
  80736. }
  80737. positions.push(p.x, 0, p.y);
  80738. positions.push(p.x, -depth, p.y);
  80739. positions.push(p1.x, 0, p1.y);
  80740. positions.push(p1.x, -depth, p1.y);
  80741. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80742. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80743. var v3 = v2.subtract(v1);
  80744. var v4 = new BABYLON.Vector3(0, 1, 0);
  80745. var vn = BABYLON.Vector3.Cross(v3, v4);
  80746. vn = vn.normalize();
  80747. uvs.push(ulength / bounds.width, 0);
  80748. uvs.push(ulength / bounds.width, 1);
  80749. ulength += v3.length();
  80750. uvs.push((ulength / bounds.width), 0);
  80751. uvs.push((ulength / bounds.width), 1);
  80752. if (!flip) {
  80753. normals.push(-vn.x, -vn.y, -vn.z);
  80754. normals.push(-vn.x, -vn.y, -vn.z);
  80755. normals.push(-vn.x, -vn.y, -vn.z);
  80756. normals.push(-vn.x, -vn.y, -vn.z);
  80757. indices.push(StartIndex);
  80758. indices.push(StartIndex + 1);
  80759. indices.push(StartIndex + 2);
  80760. indices.push(StartIndex + 1);
  80761. indices.push(StartIndex + 3);
  80762. indices.push(StartIndex + 2);
  80763. }
  80764. else {
  80765. normals.push(vn.x, vn.y, vn.z);
  80766. normals.push(vn.x, vn.y, vn.z);
  80767. normals.push(vn.x, vn.y, vn.z);
  80768. normals.push(vn.x, vn.y, vn.z);
  80769. indices.push(StartIndex);
  80770. indices.push(StartIndex + 2);
  80771. indices.push(StartIndex + 1);
  80772. indices.push(StartIndex + 1);
  80773. indices.push(StartIndex + 2);
  80774. indices.push(StartIndex + 3);
  80775. }
  80776. StartIndex += 4;
  80777. }
  80778. ;
  80779. };
  80780. return PolygonMeshBuilder;
  80781. }());
  80782. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80783. })(BABYLON || (BABYLON = {}));
  80784. //# sourceMappingURL=babylon.polygonMesh.js.map
  80785. var BABYLON;
  80786. (function (BABYLON) {
  80787. // Unique ID when we import meshes from Babylon to CSG
  80788. var currentCSGMeshId = 0;
  80789. // # class Vertex
  80790. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80791. // one to provide additional features like texture coordinates and vertex
  80792. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80793. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80794. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80795. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80796. // is not used anywhere else.
  80797. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80798. var Vertex = /** @class */ (function () {
  80799. function Vertex(pos, normal, uv) {
  80800. this.pos = pos;
  80801. this.normal = normal;
  80802. this.uv = uv;
  80803. }
  80804. Vertex.prototype.clone = function () {
  80805. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80806. };
  80807. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80808. // orientation of a polygon is flipped.
  80809. Vertex.prototype.flip = function () {
  80810. this.normal = this.normal.scale(-1);
  80811. };
  80812. // Create a new vertex between this vertex and `other` by linearly
  80813. // interpolating all properties using a parameter of `t`. Subclasses should
  80814. // override this to interpolate additional properties.
  80815. Vertex.prototype.interpolate = function (other, t) {
  80816. 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));
  80817. };
  80818. return Vertex;
  80819. }());
  80820. // # class Plane
  80821. // Represents a plane in 3D space.
  80822. var Plane = /** @class */ (function () {
  80823. function Plane(normal, w) {
  80824. this.normal = normal;
  80825. this.w = w;
  80826. }
  80827. Plane.FromPoints = function (a, b, c) {
  80828. var v0 = c.subtract(a);
  80829. var v1 = b.subtract(a);
  80830. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  80831. return null;
  80832. }
  80833. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  80834. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  80835. };
  80836. Plane.prototype.clone = function () {
  80837. return new Plane(this.normal.clone(), this.w);
  80838. };
  80839. Plane.prototype.flip = function () {
  80840. this.normal.scaleInPlace(-1);
  80841. this.w = -this.w;
  80842. };
  80843. // Split `polygon` by this plane if needed, then put the polygon or polygon
  80844. // fragments in the appropriate lists. Coplanar polygons go into either
  80845. // `coplanarFront` or `coplanarBack` depending on their orientation with
  80846. // respect to this plane. Polygons in front or in back of this plane go into
  80847. // either `front` or `back`.
  80848. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  80849. var COPLANAR = 0;
  80850. var FRONT = 1;
  80851. var BACK = 2;
  80852. var SPANNING = 3;
  80853. // Classify each point as well as the entire polygon into one of the above
  80854. // four classes.
  80855. var polygonType = 0;
  80856. var types = [];
  80857. var i;
  80858. var t;
  80859. for (i = 0; i < polygon.vertices.length; i++) {
  80860. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  80861. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  80862. polygonType |= type;
  80863. types.push(type);
  80864. }
  80865. // Put the polygon in the correct list, splitting it when necessary.
  80866. switch (polygonType) {
  80867. case COPLANAR:
  80868. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  80869. break;
  80870. case FRONT:
  80871. front.push(polygon);
  80872. break;
  80873. case BACK:
  80874. back.push(polygon);
  80875. break;
  80876. case SPANNING:
  80877. var f = [], b = [];
  80878. for (i = 0; i < polygon.vertices.length; i++) {
  80879. var j = (i + 1) % polygon.vertices.length;
  80880. var ti = types[i], tj = types[j];
  80881. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  80882. if (ti !== BACK)
  80883. f.push(vi);
  80884. if (ti !== FRONT)
  80885. b.push(ti !== BACK ? vi.clone() : vi);
  80886. if ((ti | tj) === SPANNING) {
  80887. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  80888. var v = vi.interpolate(vj, t);
  80889. f.push(v);
  80890. b.push(v.clone());
  80891. }
  80892. }
  80893. var poly;
  80894. if (f.length >= 3) {
  80895. poly = new Polygon(f, polygon.shared);
  80896. if (poly.plane)
  80897. front.push(poly);
  80898. }
  80899. if (b.length >= 3) {
  80900. poly = new Polygon(b, polygon.shared);
  80901. if (poly.plane)
  80902. back.push(poly);
  80903. }
  80904. break;
  80905. }
  80906. };
  80907. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  80908. // point is on the plane.
  80909. Plane.EPSILON = 1e-5;
  80910. return Plane;
  80911. }());
  80912. // # class Polygon
  80913. // Represents a convex polygon. The vertices used to initialize a polygon must
  80914. // be coplanar and form a convex loop.
  80915. //
  80916. // Each convex polygon has a `shared` property, which is shared between all
  80917. // polygons that are clones of each other or were split from the same polygon.
  80918. // This can be used to define per-polygon properties (such as surface color).
  80919. var Polygon = /** @class */ (function () {
  80920. function Polygon(vertices, shared) {
  80921. this.vertices = vertices;
  80922. this.shared = shared;
  80923. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  80924. }
  80925. Polygon.prototype.clone = function () {
  80926. var vertices = this.vertices.map(function (v) { return v.clone(); });
  80927. return new Polygon(vertices, this.shared);
  80928. };
  80929. Polygon.prototype.flip = function () {
  80930. this.vertices.reverse().map(function (v) { v.flip(); });
  80931. this.plane.flip();
  80932. };
  80933. return Polygon;
  80934. }());
  80935. // # class Node
  80936. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  80937. // by picking a polygon to split along. That polygon (and all other coplanar
  80938. // polygons) are added directly to that node and the other polygons are added to
  80939. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  80940. // no distinction between internal and leaf nodes.
  80941. var Node = /** @class */ (function () {
  80942. function Node(polygons) {
  80943. this.plane = null;
  80944. this.front = null;
  80945. this.back = null;
  80946. this.polygons = new Array();
  80947. if (polygons) {
  80948. this.build(polygons);
  80949. }
  80950. }
  80951. Node.prototype.clone = function () {
  80952. var node = new Node();
  80953. node.plane = this.plane && this.plane.clone();
  80954. node.front = this.front && this.front.clone();
  80955. node.back = this.back && this.back.clone();
  80956. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  80957. return node;
  80958. };
  80959. // Convert solid space to empty space and empty space to solid space.
  80960. Node.prototype.invert = function () {
  80961. for (var i = 0; i < this.polygons.length; i++) {
  80962. this.polygons[i].flip();
  80963. }
  80964. if (this.plane) {
  80965. this.plane.flip();
  80966. }
  80967. if (this.front) {
  80968. this.front.invert();
  80969. }
  80970. if (this.back) {
  80971. this.back.invert();
  80972. }
  80973. var temp = this.front;
  80974. this.front = this.back;
  80975. this.back = temp;
  80976. };
  80977. // Recursively remove all polygons in `polygons` that are inside this BSP
  80978. // tree.
  80979. Node.prototype.clipPolygons = function (polygons) {
  80980. if (!this.plane)
  80981. return polygons.slice();
  80982. var front = new Array(), back = new Array();
  80983. for (var i = 0; i < polygons.length; i++) {
  80984. this.plane.splitPolygon(polygons[i], front, back, front, back);
  80985. }
  80986. if (this.front) {
  80987. front = this.front.clipPolygons(front);
  80988. }
  80989. if (this.back) {
  80990. back = this.back.clipPolygons(back);
  80991. }
  80992. else {
  80993. back = [];
  80994. }
  80995. return front.concat(back);
  80996. };
  80997. // Remove all polygons in this BSP tree that are inside the other BSP tree
  80998. // `bsp`.
  80999. Node.prototype.clipTo = function (bsp) {
  81000. this.polygons = bsp.clipPolygons(this.polygons);
  81001. if (this.front)
  81002. this.front.clipTo(bsp);
  81003. if (this.back)
  81004. this.back.clipTo(bsp);
  81005. };
  81006. // Return a list of all polygons in this BSP tree.
  81007. Node.prototype.allPolygons = function () {
  81008. var polygons = this.polygons.slice();
  81009. if (this.front)
  81010. polygons = polygons.concat(this.front.allPolygons());
  81011. if (this.back)
  81012. polygons = polygons.concat(this.back.allPolygons());
  81013. return polygons;
  81014. };
  81015. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  81016. // new polygons are filtered down to the bottom of the tree and become new
  81017. // nodes there. Each set of polygons is partitioned using the first polygon
  81018. // (no heuristic is used to pick a good split).
  81019. Node.prototype.build = function (polygons) {
  81020. if (!polygons.length)
  81021. return;
  81022. if (!this.plane)
  81023. this.plane = polygons[0].plane.clone();
  81024. var front = new Array(), back = new Array();
  81025. for (var i = 0; i < polygons.length; i++) {
  81026. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  81027. }
  81028. if (front.length) {
  81029. if (!this.front)
  81030. this.front = new Node();
  81031. this.front.build(front);
  81032. }
  81033. if (back.length) {
  81034. if (!this.back)
  81035. this.back = new Node();
  81036. this.back.build(back);
  81037. }
  81038. };
  81039. return Node;
  81040. }());
  81041. var CSG = /** @class */ (function () {
  81042. function CSG() {
  81043. this.polygons = new Array();
  81044. }
  81045. // Convert BABYLON.Mesh to BABYLON.CSG
  81046. CSG.FromMesh = function (mesh) {
  81047. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  81048. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  81049. if (mesh instanceof BABYLON.Mesh) {
  81050. mesh.computeWorldMatrix(true);
  81051. matrix = mesh.getWorldMatrix();
  81052. meshPosition = mesh.position.clone();
  81053. meshRotation = mesh.rotation.clone();
  81054. if (mesh.rotationQuaternion) {
  81055. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  81056. }
  81057. meshScaling = mesh.scaling.clone();
  81058. }
  81059. else {
  81060. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  81061. }
  81062. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81063. var subMeshes = mesh.subMeshes;
  81064. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  81065. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  81066. vertices = [];
  81067. for (var j = 0; j < 3; j++) {
  81068. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  81069. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  81070. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  81071. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  81072. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  81073. vertex = new Vertex(position, normal, uv);
  81074. vertices.push(vertex);
  81075. }
  81076. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  81077. // To handle the case of degenerated triangle
  81078. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  81079. if (polygon.plane)
  81080. polygons.push(polygon);
  81081. }
  81082. }
  81083. var csg = CSG.FromPolygons(polygons);
  81084. csg.matrix = matrix;
  81085. csg.position = meshPosition;
  81086. csg.rotation = meshRotation;
  81087. csg.scaling = meshScaling;
  81088. csg.rotationQuaternion = meshRotationQuaternion;
  81089. currentCSGMeshId++;
  81090. return csg;
  81091. };
  81092. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81093. CSG.FromPolygons = function (polygons) {
  81094. var csg = new CSG();
  81095. csg.polygons = polygons;
  81096. return csg;
  81097. };
  81098. CSG.prototype.clone = function () {
  81099. var csg = new CSG();
  81100. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81101. csg.copyTransformAttributes(this);
  81102. return csg;
  81103. };
  81104. CSG.prototype.union = function (csg) {
  81105. var a = new Node(this.clone().polygons);
  81106. var b = new Node(csg.clone().polygons);
  81107. a.clipTo(b);
  81108. b.clipTo(a);
  81109. b.invert();
  81110. b.clipTo(a);
  81111. b.invert();
  81112. a.build(b.allPolygons());
  81113. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81114. };
  81115. CSG.prototype.unionInPlace = function (csg) {
  81116. var a = new Node(this.polygons);
  81117. var b = new Node(csg.polygons);
  81118. a.clipTo(b);
  81119. b.clipTo(a);
  81120. b.invert();
  81121. b.clipTo(a);
  81122. b.invert();
  81123. a.build(b.allPolygons());
  81124. this.polygons = a.allPolygons();
  81125. };
  81126. CSG.prototype.subtract = function (csg) {
  81127. var a = new Node(this.clone().polygons);
  81128. var b = new Node(csg.clone().polygons);
  81129. a.invert();
  81130. a.clipTo(b);
  81131. b.clipTo(a);
  81132. b.invert();
  81133. b.clipTo(a);
  81134. b.invert();
  81135. a.build(b.allPolygons());
  81136. a.invert();
  81137. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81138. };
  81139. CSG.prototype.subtractInPlace = function (csg) {
  81140. var a = new Node(this.polygons);
  81141. var b = new Node(csg.polygons);
  81142. a.invert();
  81143. a.clipTo(b);
  81144. b.clipTo(a);
  81145. b.invert();
  81146. b.clipTo(a);
  81147. b.invert();
  81148. a.build(b.allPolygons());
  81149. a.invert();
  81150. this.polygons = a.allPolygons();
  81151. };
  81152. CSG.prototype.intersect = function (csg) {
  81153. var a = new Node(this.clone().polygons);
  81154. var b = new Node(csg.clone().polygons);
  81155. a.invert();
  81156. b.clipTo(a);
  81157. b.invert();
  81158. a.clipTo(b);
  81159. b.clipTo(a);
  81160. a.build(b.allPolygons());
  81161. a.invert();
  81162. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81163. };
  81164. CSG.prototype.intersectInPlace = function (csg) {
  81165. var a = new Node(this.polygons);
  81166. var b = new Node(csg.polygons);
  81167. a.invert();
  81168. b.clipTo(a);
  81169. b.invert();
  81170. a.clipTo(b);
  81171. b.clipTo(a);
  81172. a.build(b.allPolygons());
  81173. a.invert();
  81174. this.polygons = a.allPolygons();
  81175. };
  81176. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81177. // not modified.
  81178. CSG.prototype.inverse = function () {
  81179. var csg = this.clone();
  81180. csg.inverseInPlace();
  81181. return csg;
  81182. };
  81183. CSG.prototype.inverseInPlace = function () {
  81184. this.polygons.map(function (p) { p.flip(); });
  81185. };
  81186. // This is used to keep meshes transformations so they can be restored
  81187. // when we build back a Babylon Mesh
  81188. // NB : All CSG operations are performed in world coordinates
  81189. CSG.prototype.copyTransformAttributes = function (csg) {
  81190. this.matrix = csg.matrix;
  81191. this.position = csg.position;
  81192. this.rotation = csg.rotation;
  81193. this.scaling = csg.scaling;
  81194. this.rotationQuaternion = csg.rotationQuaternion;
  81195. return this;
  81196. };
  81197. // Build Raw mesh from CSG
  81198. // Coordinates here are in world space
  81199. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81200. var matrix = this.matrix.clone();
  81201. matrix.invert();
  81202. 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;
  81203. if (keepSubMeshes) {
  81204. // Sort Polygons, since subMeshes are indices range
  81205. polygons.sort(function (a, b) {
  81206. if (a.shared.meshId === b.shared.meshId) {
  81207. return a.shared.subMeshId - b.shared.subMeshId;
  81208. }
  81209. else {
  81210. return a.shared.meshId - b.shared.meshId;
  81211. }
  81212. });
  81213. }
  81214. for (var i = 0, il = polygons.length; i < il; i++) {
  81215. polygon = polygons[i];
  81216. // Building SubMeshes
  81217. if (!subMesh_dict[polygon.shared.meshId]) {
  81218. subMesh_dict[polygon.shared.meshId] = {};
  81219. }
  81220. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81221. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81222. indexStart: +Infinity,
  81223. indexEnd: -Infinity,
  81224. materialIndex: polygon.shared.materialIndex
  81225. };
  81226. }
  81227. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81228. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81229. polygonIndices[0] = 0;
  81230. polygonIndices[1] = j - 1;
  81231. polygonIndices[2] = j;
  81232. for (var k = 0; k < 3; k++) {
  81233. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81234. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81235. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81236. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81237. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81238. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81239. // Check if 2 points can be merged
  81240. if (!(typeof vertex_idx !== 'undefined' &&
  81241. normals[vertex_idx * 3] === localNormal.x &&
  81242. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81243. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81244. uvs[vertex_idx * 2] === uv.x &&
  81245. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81246. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81247. uvs.push(uv.x, uv.y);
  81248. normals.push(normal.x, normal.y, normal.z);
  81249. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81250. }
  81251. indices.push(vertex_idx);
  81252. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81253. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81254. currentIndex++;
  81255. }
  81256. }
  81257. }
  81258. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81259. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81260. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81261. mesh.setIndices(indices, null);
  81262. if (keepSubMeshes) {
  81263. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81264. var materialIndexOffset = 0, materialMaxIndex;
  81265. mesh.subMeshes = new Array();
  81266. for (var m in subMesh_dict) {
  81267. materialMaxIndex = -1;
  81268. for (var sm in subMesh_dict[m]) {
  81269. subMesh_obj = subMesh_dict[m][sm];
  81270. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81271. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81272. }
  81273. materialIndexOffset += ++materialMaxIndex;
  81274. }
  81275. }
  81276. return mesh;
  81277. };
  81278. // Build Mesh from CSG taking material and transforms into account
  81279. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81280. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81281. mesh.material = material;
  81282. mesh.position.copyFrom(this.position);
  81283. mesh.rotation.copyFrom(this.rotation);
  81284. if (this.rotationQuaternion) {
  81285. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81286. }
  81287. mesh.scaling.copyFrom(this.scaling);
  81288. mesh.computeWorldMatrix(true);
  81289. return mesh;
  81290. };
  81291. return CSG;
  81292. }());
  81293. BABYLON.CSG = CSG;
  81294. })(BABYLON || (BABYLON = {}));
  81295. //# sourceMappingURL=babylon.csg.js.map
  81296. var BABYLON;
  81297. (function (BABYLON) {
  81298. var LensFlare = /** @class */ (function () {
  81299. function LensFlare(size, position, color, imgUrl, system) {
  81300. this.size = size;
  81301. this.position = position;
  81302. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81303. this.color = color || new BABYLON.Color3(1, 1, 1);
  81304. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81305. this._system = system;
  81306. system.lensFlares.push(this);
  81307. }
  81308. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81309. return new LensFlare(size, position, color, imgUrl, system);
  81310. };
  81311. LensFlare.prototype.dispose = function () {
  81312. if (this.texture) {
  81313. this.texture.dispose();
  81314. }
  81315. // Remove from scene
  81316. var index = this._system.lensFlares.indexOf(this);
  81317. this._system.lensFlares.splice(index, 1);
  81318. };
  81319. ;
  81320. return LensFlare;
  81321. }());
  81322. BABYLON.LensFlare = LensFlare;
  81323. })(BABYLON || (BABYLON = {}));
  81324. //# sourceMappingURL=babylon.lensFlare.js.map
  81325. var BABYLON;
  81326. (function (BABYLON) {
  81327. var LensFlareSystem = /** @class */ (function () {
  81328. function LensFlareSystem(name, emitter, scene) {
  81329. this.name = name;
  81330. this.lensFlares = new Array();
  81331. this.borderLimit = 300;
  81332. this.viewportBorder = 0;
  81333. this.layerMask = 0x0FFFFFFF;
  81334. this._vertexBuffers = {};
  81335. this._isEnabled = true;
  81336. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81337. this._emitter = emitter;
  81338. this.id = name;
  81339. scene.lensFlareSystems.push(this);
  81340. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81341. var engine = scene.getEngine();
  81342. // VBO
  81343. var vertices = [];
  81344. vertices.push(1, 1);
  81345. vertices.push(-1, 1);
  81346. vertices.push(-1, -1);
  81347. vertices.push(1, -1);
  81348. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81349. // Indices
  81350. var indices = [];
  81351. indices.push(0);
  81352. indices.push(1);
  81353. indices.push(2);
  81354. indices.push(0);
  81355. indices.push(2);
  81356. indices.push(3);
  81357. this._indexBuffer = engine.createIndexBuffer(indices);
  81358. // Effects
  81359. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81360. }
  81361. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81362. get: function () {
  81363. return this._isEnabled;
  81364. },
  81365. set: function (value) {
  81366. this._isEnabled = value;
  81367. },
  81368. enumerable: true,
  81369. configurable: true
  81370. });
  81371. LensFlareSystem.prototype.getScene = function () {
  81372. return this._scene;
  81373. };
  81374. LensFlareSystem.prototype.getEmitter = function () {
  81375. return this._emitter;
  81376. };
  81377. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81378. this._emitter = newEmitter;
  81379. };
  81380. LensFlareSystem.prototype.getEmitterPosition = function () {
  81381. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81382. };
  81383. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81384. var position = this.getEmitterPosition();
  81385. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81386. this._positionX = position.x;
  81387. this._positionY = position.y;
  81388. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81389. if (this.viewportBorder > 0) {
  81390. globalViewport.x -= this.viewportBorder;
  81391. globalViewport.y -= this.viewportBorder;
  81392. globalViewport.width += this.viewportBorder * 2;
  81393. globalViewport.height += this.viewportBorder * 2;
  81394. position.x += this.viewportBorder;
  81395. position.y += this.viewportBorder;
  81396. this._positionX += this.viewportBorder;
  81397. this._positionY += this.viewportBorder;
  81398. }
  81399. if (position.z > 0) {
  81400. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81401. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81402. return true;
  81403. }
  81404. return true;
  81405. }
  81406. return false;
  81407. };
  81408. LensFlareSystem.prototype._isVisible = function () {
  81409. if (!this._isEnabled || !this._scene.activeCamera) {
  81410. return false;
  81411. }
  81412. var emitterPosition = this.getEmitterPosition();
  81413. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81414. var distance = direction.length();
  81415. direction.normalize();
  81416. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81417. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81418. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81419. };
  81420. LensFlareSystem.prototype.render = function () {
  81421. if (!this._effect.isReady() || !this._scene.activeCamera)
  81422. return false;
  81423. var engine = this._scene.getEngine();
  81424. var viewport = this._scene.activeCamera.viewport;
  81425. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81426. // Position
  81427. if (!this.computeEffectivePosition(globalViewport)) {
  81428. return false;
  81429. }
  81430. // Visibility
  81431. if (!this._isVisible()) {
  81432. return false;
  81433. }
  81434. // Intensity
  81435. var awayX;
  81436. var awayY;
  81437. if (this._positionX < this.borderLimit + globalViewport.x) {
  81438. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81439. }
  81440. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81441. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81442. }
  81443. else {
  81444. awayX = 0;
  81445. }
  81446. if (this._positionY < this.borderLimit + globalViewport.y) {
  81447. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81448. }
  81449. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81450. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81451. }
  81452. else {
  81453. awayY = 0;
  81454. }
  81455. var away = (awayX > awayY) ? awayX : awayY;
  81456. away -= this.viewportBorder;
  81457. if (away > this.borderLimit) {
  81458. away = this.borderLimit;
  81459. }
  81460. var intensity = 1.0 - (away / this.borderLimit);
  81461. if (intensity < 0) {
  81462. return false;
  81463. }
  81464. if (intensity > 1.0) {
  81465. intensity = 1.0;
  81466. }
  81467. if (this.viewportBorder > 0) {
  81468. globalViewport.x += this.viewportBorder;
  81469. globalViewport.y += this.viewportBorder;
  81470. globalViewport.width -= this.viewportBorder * 2;
  81471. globalViewport.height -= this.viewportBorder * 2;
  81472. this._positionX -= this.viewportBorder;
  81473. this._positionY -= this.viewportBorder;
  81474. }
  81475. // Position
  81476. var centerX = globalViewport.x + globalViewport.width / 2;
  81477. var centerY = globalViewport.y + globalViewport.height / 2;
  81478. var distX = centerX - this._positionX;
  81479. var distY = centerY - this._positionY;
  81480. // Effects
  81481. engine.enableEffect(this._effect);
  81482. engine.setState(false);
  81483. engine.setDepthBuffer(false);
  81484. // VBOs
  81485. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81486. // Flares
  81487. for (var index = 0; index < this.lensFlares.length; index++) {
  81488. var flare = this.lensFlares[index];
  81489. engine.setAlphaMode(flare.alphaMode);
  81490. var x = centerX - (distX * flare.position);
  81491. var y = centerY - (distY * flare.position);
  81492. var cw = flare.size;
  81493. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  81494. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  81495. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  81496. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  81497. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  81498. // Texture
  81499. this._effect.setTexture("textureSampler", flare.texture);
  81500. // Color
  81501. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  81502. // Draw order
  81503. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81504. }
  81505. engine.setDepthBuffer(true);
  81506. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81507. return true;
  81508. };
  81509. LensFlareSystem.prototype.dispose = function () {
  81510. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81511. if (vertexBuffer) {
  81512. vertexBuffer.dispose();
  81513. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81514. }
  81515. if (this._indexBuffer) {
  81516. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81517. this._indexBuffer = null;
  81518. }
  81519. while (this.lensFlares.length) {
  81520. this.lensFlares[0].dispose();
  81521. }
  81522. // Remove from scene
  81523. var index = this._scene.lensFlareSystems.indexOf(this);
  81524. this._scene.lensFlareSystems.splice(index, 1);
  81525. };
  81526. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81527. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81528. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81529. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81530. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81531. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81532. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81533. var parsedFlare = parsedLensFlareSystem.flares[index];
  81534. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81535. }
  81536. return lensFlareSystem;
  81537. };
  81538. LensFlareSystem.prototype.serialize = function () {
  81539. var serializationObject = {};
  81540. serializationObject.id = this.id;
  81541. serializationObject.name = this.name;
  81542. serializationObject.emitterId = this.getEmitter().id;
  81543. serializationObject.borderLimit = this.borderLimit;
  81544. serializationObject.flares = [];
  81545. for (var index = 0; index < this.lensFlares.length; index++) {
  81546. var flare = this.lensFlares[index];
  81547. serializationObject.flares.push({
  81548. size: flare.size,
  81549. position: flare.position,
  81550. color: flare.color.asArray(),
  81551. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81552. });
  81553. }
  81554. return serializationObject;
  81555. };
  81556. return LensFlareSystem;
  81557. }());
  81558. BABYLON.LensFlareSystem = LensFlareSystem;
  81559. })(BABYLON || (BABYLON = {}));
  81560. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81561. var BABYLON;
  81562. (function (BABYLON) {
  81563. /**
  81564. * This is a holder class for the physics joint created by the physics plugin.
  81565. * It holds a set of functions to control the underlying joint.
  81566. */
  81567. var PhysicsJoint = /** @class */ (function () {
  81568. function PhysicsJoint(type, jointData) {
  81569. this.type = type;
  81570. this.jointData = jointData;
  81571. jointData.nativeParams = jointData.nativeParams || {};
  81572. }
  81573. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81574. get: function () {
  81575. return this._physicsJoint;
  81576. },
  81577. set: function (newJoint) {
  81578. if (this._physicsJoint) {
  81579. //remove from the wolrd
  81580. }
  81581. this._physicsJoint = newJoint;
  81582. },
  81583. enumerable: true,
  81584. configurable: true
  81585. });
  81586. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81587. set: function (physicsPlugin) {
  81588. this._physicsPlugin = physicsPlugin;
  81589. },
  81590. enumerable: true,
  81591. configurable: true
  81592. });
  81593. /**
  81594. * Execute a function that is physics-plugin specific.
  81595. * @param {Function} func the function that will be executed.
  81596. * It accepts two parameters: the physics world and the physics joint.
  81597. */
  81598. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81599. func(this._physicsPlugin.world, this._physicsJoint);
  81600. };
  81601. //TODO check if the native joints are the same
  81602. //Joint Types
  81603. PhysicsJoint.DistanceJoint = 0;
  81604. PhysicsJoint.HingeJoint = 1;
  81605. PhysicsJoint.BallAndSocketJoint = 2;
  81606. PhysicsJoint.WheelJoint = 3;
  81607. PhysicsJoint.SliderJoint = 4;
  81608. //OIMO
  81609. PhysicsJoint.PrismaticJoint = 5;
  81610. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81611. PhysicsJoint.UniversalJoint = 6;
  81612. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81613. //Cannon
  81614. //Similar to a Ball-Joint. Different in params
  81615. PhysicsJoint.PointToPointJoint = 8;
  81616. //Cannon only at the moment
  81617. PhysicsJoint.SpringJoint = 9;
  81618. PhysicsJoint.LockJoint = 10;
  81619. return PhysicsJoint;
  81620. }());
  81621. BABYLON.PhysicsJoint = PhysicsJoint;
  81622. /**
  81623. * A class representing a physics distance joint.
  81624. */
  81625. var DistanceJoint = /** @class */ (function (_super) {
  81626. __extends(DistanceJoint, _super);
  81627. function DistanceJoint(jointData) {
  81628. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81629. }
  81630. /**
  81631. * Update the predefined distance.
  81632. */
  81633. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81634. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81635. };
  81636. return DistanceJoint;
  81637. }(PhysicsJoint));
  81638. BABYLON.DistanceJoint = DistanceJoint;
  81639. var MotorEnabledJoint = /** @class */ (function (_super) {
  81640. __extends(MotorEnabledJoint, _super);
  81641. function MotorEnabledJoint(type, jointData) {
  81642. return _super.call(this, type, jointData) || this;
  81643. }
  81644. /**
  81645. * Set the motor values.
  81646. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81647. * @param {number} force the force to apply
  81648. * @param {number} maxForce max force for this motor.
  81649. */
  81650. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81651. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81652. };
  81653. /**
  81654. * Set the motor's limits.
  81655. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81656. */
  81657. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81658. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81659. };
  81660. return MotorEnabledJoint;
  81661. }(PhysicsJoint));
  81662. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81663. /**
  81664. * This class represents a single hinge physics joint
  81665. */
  81666. var HingeJoint = /** @class */ (function (_super) {
  81667. __extends(HingeJoint, _super);
  81668. function HingeJoint(jointData) {
  81669. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81670. }
  81671. /**
  81672. * Set the motor values.
  81673. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81674. * @param {number} force the force to apply
  81675. * @param {number} maxForce max force for this motor.
  81676. */
  81677. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81678. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81679. };
  81680. /**
  81681. * Set the motor's limits.
  81682. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81683. */
  81684. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81685. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81686. };
  81687. return HingeJoint;
  81688. }(MotorEnabledJoint));
  81689. BABYLON.HingeJoint = HingeJoint;
  81690. /**
  81691. * This class represents a dual hinge physics joint (same as wheel joint)
  81692. */
  81693. var Hinge2Joint = /** @class */ (function (_super) {
  81694. __extends(Hinge2Joint, _super);
  81695. function Hinge2Joint(jointData) {
  81696. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81697. }
  81698. /**
  81699. * Set the motor values.
  81700. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81701. * @param {number} force the force to apply
  81702. * @param {number} maxForce max force for this motor.
  81703. * @param {motorIndex} the motor's index, 0 or 1.
  81704. */
  81705. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81706. if (motorIndex === void 0) { motorIndex = 0; }
  81707. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81708. };
  81709. /**
  81710. * Set the motor limits.
  81711. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81712. * @param {number} upperLimit the upper limit
  81713. * @param {number} lowerLimit lower limit
  81714. * @param {motorIndex} the motor's index, 0 or 1.
  81715. */
  81716. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81717. if (motorIndex === void 0) { motorIndex = 0; }
  81718. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81719. };
  81720. return Hinge2Joint;
  81721. }(MotorEnabledJoint));
  81722. BABYLON.Hinge2Joint = Hinge2Joint;
  81723. })(BABYLON || (BABYLON = {}));
  81724. //# sourceMappingURL=babylon.physicsJoint.js.map
  81725. var BABYLON;
  81726. (function (BABYLON) {
  81727. var PhysicsImpostor = /** @class */ (function () {
  81728. function PhysicsImpostor(object, type, _options, _scene) {
  81729. if (_options === void 0) { _options = { mass: 0 }; }
  81730. var _this = this;
  81731. this.object = object;
  81732. this.type = type;
  81733. this._options = _options;
  81734. this._scene = _scene;
  81735. this._bodyUpdateRequired = false;
  81736. this._onBeforePhysicsStepCallbacks = new Array();
  81737. this._onAfterPhysicsStepCallbacks = new Array();
  81738. this._onPhysicsCollideCallbacks = [];
  81739. this._deltaPosition = BABYLON.Vector3.Zero();
  81740. this._isDisposed = false;
  81741. //temp variables for parent rotation calculations
  81742. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81743. this._tmpQuat = new BABYLON.Quaternion();
  81744. this._tmpQuat2 = new BABYLON.Quaternion();
  81745. /**
  81746. * this function is executed by the physics engine.
  81747. */
  81748. this.beforeStep = function () {
  81749. if (!_this._physicsEngine) {
  81750. return;
  81751. }
  81752. _this.object.translate(_this._deltaPosition, -1);
  81753. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81754. _this.object.computeWorldMatrix(false);
  81755. if (_this.object.parent && _this.object.rotationQuaternion) {
  81756. _this.getParentsRotation();
  81757. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81758. }
  81759. else {
  81760. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81761. }
  81762. if (!_this._options.disableBidirectionalTransformation) {
  81763. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81764. }
  81765. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81766. func(_this);
  81767. });
  81768. };
  81769. /**
  81770. * this function is executed by the physics engine.
  81771. */
  81772. this.afterStep = function () {
  81773. if (!_this._physicsEngine) {
  81774. return;
  81775. }
  81776. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81777. func(_this);
  81778. });
  81779. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81780. // object has now its world rotation. needs to be converted to local.
  81781. if (_this.object.parent && _this.object.rotationQuaternion) {
  81782. _this.getParentsRotation();
  81783. _this._tmpQuat.conjugateInPlace();
  81784. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81785. }
  81786. // take the position set and make it the absolute position of this object.
  81787. _this.object.setAbsolutePosition(_this.object.position);
  81788. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81789. _this.object.translate(_this._deltaPosition, 1);
  81790. };
  81791. /**
  81792. * Legacy collision detection event support
  81793. */
  81794. this.onCollideEvent = null;
  81795. //event and body object due to cannon's event-based architecture.
  81796. this.onCollide = function (e) {
  81797. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81798. return;
  81799. }
  81800. if (!_this._physicsEngine) {
  81801. return;
  81802. }
  81803. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81804. if (otherImpostor) {
  81805. // Legacy collision detection event support
  81806. if (_this.onCollideEvent) {
  81807. _this.onCollideEvent(_this, otherImpostor);
  81808. }
  81809. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81810. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81811. }).forEach(function (obj) {
  81812. obj.callback(_this, otherImpostor);
  81813. });
  81814. }
  81815. };
  81816. //sanity check!
  81817. if (!this.object) {
  81818. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81819. return;
  81820. }
  81821. //legacy support for old syntax.
  81822. if (!this._scene && object.getScene) {
  81823. this._scene = object.getScene();
  81824. }
  81825. if (!this._scene) {
  81826. return;
  81827. }
  81828. this._physicsEngine = this._scene.getPhysicsEngine();
  81829. if (!this._physicsEngine) {
  81830. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  81831. }
  81832. else {
  81833. //set the object's quaternion, if not set
  81834. if (!this.object.rotationQuaternion) {
  81835. if (this.object.rotation) {
  81836. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  81837. }
  81838. else {
  81839. this.object.rotationQuaternion = new BABYLON.Quaternion();
  81840. }
  81841. }
  81842. //default options params
  81843. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  81844. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  81845. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  81846. this._joints = [];
  81847. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  81848. if (!this.object.parent || this._options.ignoreParent) {
  81849. this._init();
  81850. }
  81851. else if (this.object.parent.physicsImpostor) {
  81852. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  81853. }
  81854. }
  81855. }
  81856. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  81857. get: function () {
  81858. return this._isDisposed;
  81859. },
  81860. enumerable: true,
  81861. configurable: true
  81862. });
  81863. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  81864. get: function () {
  81865. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  81866. },
  81867. set: function (value) {
  81868. this.setMass(value);
  81869. },
  81870. enumerable: true,
  81871. configurable: true
  81872. });
  81873. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  81874. get: function () {
  81875. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  81876. },
  81877. set: function (value) {
  81878. if (!this._physicsEngine) {
  81879. return;
  81880. }
  81881. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  81882. },
  81883. enumerable: true,
  81884. configurable: true
  81885. });
  81886. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  81887. get: function () {
  81888. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  81889. },
  81890. set: function (value) {
  81891. if (!this._physicsEngine) {
  81892. return;
  81893. }
  81894. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  81895. },
  81896. enumerable: true,
  81897. configurable: true
  81898. });
  81899. /**
  81900. * This function will completly initialize this impostor.
  81901. * It will create a new body - but only if this mesh has no parent.
  81902. * If it has, this impostor will not be used other than to define the impostor
  81903. * of the child mesh.
  81904. */
  81905. PhysicsImpostor.prototype._init = function () {
  81906. if (!this._physicsEngine) {
  81907. return;
  81908. }
  81909. this._physicsEngine.removeImpostor(this);
  81910. this.physicsBody = null;
  81911. this._parent = this._parent || this._getPhysicsParent();
  81912. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  81913. this._physicsEngine.addImpostor(this);
  81914. }
  81915. };
  81916. PhysicsImpostor.prototype._getPhysicsParent = function () {
  81917. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  81918. var parentMesh = this.object.parent;
  81919. return parentMesh.physicsImpostor;
  81920. }
  81921. return null;
  81922. };
  81923. /**
  81924. * Should a new body be generated.
  81925. */
  81926. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  81927. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  81928. };
  81929. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  81930. this.forceUpdate();
  81931. };
  81932. /**
  81933. * Force a regeneration of this or the parent's impostor's body.
  81934. * Use under cautious - This will remove all joints already implemented.
  81935. */
  81936. PhysicsImpostor.prototype.forceUpdate = function () {
  81937. this._init();
  81938. if (this.parent && !this._options.ignoreParent) {
  81939. this.parent.forceUpdate();
  81940. }
  81941. };
  81942. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  81943. /*public get mesh(): AbstractMesh {
  81944. return this._mesh;
  81945. }*/
  81946. /**
  81947. * Gets the body that holds this impostor. Either its own, or its parent.
  81948. */
  81949. get: function () {
  81950. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  81951. },
  81952. /**
  81953. * Set the physics body. Used mainly by the physics engine/plugin
  81954. */
  81955. set: function (physicsBody) {
  81956. if (this._physicsBody && this._physicsEngine) {
  81957. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  81958. }
  81959. this._physicsBody = physicsBody;
  81960. this.resetUpdateFlags();
  81961. },
  81962. enumerable: true,
  81963. configurable: true
  81964. });
  81965. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  81966. get: function () {
  81967. return !this._options.ignoreParent && this._parent ? this._parent : null;
  81968. },
  81969. set: function (value) {
  81970. this._parent = value;
  81971. },
  81972. enumerable: true,
  81973. configurable: true
  81974. });
  81975. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  81976. this._bodyUpdateRequired = false;
  81977. };
  81978. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  81979. if (this.object.getBoundingInfo) {
  81980. var q = this.object.rotationQuaternion;
  81981. //reset rotation
  81982. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  81983. //calculate the world matrix with no rotation
  81984. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81985. var boundingInfo = this.object.getBoundingInfo();
  81986. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  81987. //bring back the rotation
  81988. this.object.rotationQuaternion = q;
  81989. //calculate the world matrix with the new rotation
  81990. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81991. return size;
  81992. }
  81993. else {
  81994. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  81995. }
  81996. };
  81997. PhysicsImpostor.prototype.getObjectCenter = function () {
  81998. if (this.object.getBoundingInfo) {
  81999. var boundingInfo = this.object.getBoundingInfo();
  82000. return boundingInfo.boundingBox.centerWorld;
  82001. }
  82002. else {
  82003. return this.object.position;
  82004. }
  82005. };
  82006. /**
  82007. * Get a specific parametes from the options parameter.
  82008. */
  82009. PhysicsImpostor.prototype.getParam = function (paramName) {
  82010. return this._options[paramName];
  82011. };
  82012. /**
  82013. * Sets a specific parameter in the options given to the physics plugin
  82014. */
  82015. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  82016. this._options[paramName] = value;
  82017. this._bodyUpdateRequired = true;
  82018. };
  82019. /**
  82020. * Specifically change the body's mass option. Won't recreate the physics body object
  82021. */
  82022. PhysicsImpostor.prototype.setMass = function (mass) {
  82023. if (this.getParam("mass") !== mass) {
  82024. this.setParam("mass", mass);
  82025. }
  82026. if (this._physicsEngine) {
  82027. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  82028. }
  82029. };
  82030. PhysicsImpostor.prototype.getLinearVelocity = function () {
  82031. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  82032. };
  82033. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  82034. if (this._physicsEngine) {
  82035. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  82036. }
  82037. };
  82038. PhysicsImpostor.prototype.getAngularVelocity = function () {
  82039. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  82040. };
  82041. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  82042. if (this._physicsEngine) {
  82043. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  82044. }
  82045. };
  82046. /**
  82047. * Execute a function with the physics plugin native code.
  82048. * Provide a function the will have two variables - the world object and the physics body object.
  82049. */
  82050. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  82051. if (this._physicsEngine) {
  82052. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  82053. }
  82054. };
  82055. /**
  82056. * Register a function that will be executed before the physics world is stepping forward.
  82057. */
  82058. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  82059. this._onBeforePhysicsStepCallbacks.push(func);
  82060. };
  82061. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  82062. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  82063. if (index > -1) {
  82064. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  82065. }
  82066. else {
  82067. BABYLON.Tools.Warn("Function to remove was not found");
  82068. }
  82069. };
  82070. /**
  82071. * Register a function that will be executed after the physics step
  82072. */
  82073. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  82074. this._onAfterPhysicsStepCallbacks.push(func);
  82075. };
  82076. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  82077. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  82078. if (index > -1) {
  82079. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  82080. }
  82081. else {
  82082. BABYLON.Tools.Warn("Function to remove was not found");
  82083. }
  82084. };
  82085. /**
  82086. * register a function that will be executed when this impostor collides against a different body.
  82087. */
  82088. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82089. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82090. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82091. };
  82092. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82093. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82094. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  82095. if (index > -1) {
  82096. this._onPhysicsCollideCallbacks.splice(index, 1);
  82097. }
  82098. else {
  82099. BABYLON.Tools.Warn("Function to remove was not found");
  82100. }
  82101. };
  82102. PhysicsImpostor.prototype.getParentsRotation = function () {
  82103. var parent = this.object.parent;
  82104. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82105. while (parent) {
  82106. if (parent.rotationQuaternion) {
  82107. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82108. }
  82109. else {
  82110. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82111. }
  82112. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82113. parent = parent.parent;
  82114. }
  82115. return this._tmpQuat;
  82116. };
  82117. /**
  82118. * Apply a force
  82119. */
  82120. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82121. if (this._physicsEngine) {
  82122. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82123. }
  82124. return this;
  82125. };
  82126. /**
  82127. * Apply an impulse
  82128. */
  82129. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82130. if (this._physicsEngine) {
  82131. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82132. }
  82133. return this;
  82134. };
  82135. /**
  82136. * A help function to create a joint.
  82137. */
  82138. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82139. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82140. this.addJoint(otherImpostor, joint);
  82141. return this;
  82142. };
  82143. /**
  82144. * Add a joint to this impostor with a different impostor.
  82145. */
  82146. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82147. this._joints.push({
  82148. otherImpostor: otherImpostor,
  82149. joint: joint
  82150. });
  82151. if (this._physicsEngine) {
  82152. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82153. }
  82154. return this;
  82155. };
  82156. /**
  82157. * Will keep this body still, in a sleep mode.
  82158. */
  82159. PhysicsImpostor.prototype.sleep = function () {
  82160. if (this._physicsEngine) {
  82161. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82162. }
  82163. return this;
  82164. };
  82165. /**
  82166. * Wake the body up.
  82167. */
  82168. PhysicsImpostor.prototype.wakeUp = function () {
  82169. if (this._physicsEngine) {
  82170. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82171. }
  82172. return this;
  82173. };
  82174. PhysicsImpostor.prototype.clone = function (newObject) {
  82175. if (!newObject)
  82176. return null;
  82177. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82178. };
  82179. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82180. var _this = this;
  82181. //no dispose if no physics engine is available.
  82182. if (!this._physicsEngine) {
  82183. return;
  82184. }
  82185. this._joints.forEach(function (j) {
  82186. if (_this._physicsEngine) {
  82187. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82188. }
  82189. });
  82190. //dispose the physics body
  82191. this._physicsEngine.removeImpostor(this);
  82192. if (this.parent) {
  82193. this.parent.forceUpdate();
  82194. }
  82195. else {
  82196. /*this._object.getChildMeshes().forEach(function(mesh) {
  82197. if (mesh.physicsImpostor) {
  82198. if (disposeChildren) {
  82199. mesh.physicsImpostor.dispose();
  82200. mesh.physicsImpostor = null;
  82201. }
  82202. }
  82203. })*/
  82204. }
  82205. this._isDisposed = true;
  82206. };
  82207. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82208. this._deltaPosition.copyFrom(position);
  82209. };
  82210. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82211. if (!this._deltaRotation) {
  82212. this._deltaRotation = new BABYLON.Quaternion();
  82213. }
  82214. this._deltaRotation.copyFrom(rotation);
  82215. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82216. };
  82217. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82218. if (this._physicsEngine) {
  82219. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82220. }
  82221. return this;
  82222. };
  82223. PhysicsImpostor.prototype.getRadius = function () {
  82224. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82225. };
  82226. /**
  82227. * Sync a bone with this impostor
  82228. * @param bone The bone to sync to the impostor.
  82229. * @param boneMesh The mesh that the bone is influencing.
  82230. * @param jointPivot The pivot of the joint / bone in local space.
  82231. * @param distToJoint Optional distance from the impostor to the joint.
  82232. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82233. */
  82234. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82235. var tempVec = PhysicsImpostor._tmpVecs[0];
  82236. var mesh = this.object;
  82237. if (mesh.rotationQuaternion) {
  82238. if (adjustRotation) {
  82239. var tempQuat = PhysicsImpostor._tmpQuat;
  82240. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82241. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82242. }
  82243. else {
  82244. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82245. }
  82246. }
  82247. tempVec.x = 0;
  82248. tempVec.y = 0;
  82249. tempVec.z = 0;
  82250. if (jointPivot) {
  82251. tempVec.x = jointPivot.x;
  82252. tempVec.y = jointPivot.y;
  82253. tempVec.z = jointPivot.z;
  82254. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82255. if (distToJoint === undefined || distToJoint === null) {
  82256. distToJoint = jointPivot.length();
  82257. }
  82258. tempVec.x *= distToJoint;
  82259. tempVec.y *= distToJoint;
  82260. tempVec.z *= distToJoint;
  82261. }
  82262. if (bone.getParent()) {
  82263. tempVec.addInPlace(mesh.getAbsolutePosition());
  82264. bone.setAbsolutePosition(tempVec, boneMesh);
  82265. }
  82266. else {
  82267. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82268. boneMesh.position.x -= tempVec.x;
  82269. boneMesh.position.y -= tempVec.y;
  82270. boneMesh.position.z -= tempVec.z;
  82271. }
  82272. };
  82273. /**
  82274. * Sync impostor to a bone
  82275. * @param bone The bone that the impostor will be synced to.
  82276. * @param boneMesh The mesh that the bone is influencing.
  82277. * @param jointPivot The pivot of the joint / bone in local space.
  82278. * @param distToJoint Optional distance from the impostor to the joint.
  82279. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82280. * @param boneAxis Optional vector3 axis the bone is aligned with
  82281. */
  82282. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82283. var mesh = this.object;
  82284. if (mesh.rotationQuaternion) {
  82285. if (adjustRotation) {
  82286. var tempQuat = PhysicsImpostor._tmpQuat;
  82287. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82288. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82289. }
  82290. else {
  82291. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82292. }
  82293. }
  82294. var pos = PhysicsImpostor._tmpVecs[0];
  82295. var boneDir = PhysicsImpostor._tmpVecs[1];
  82296. if (!boneAxis) {
  82297. boneAxis = PhysicsImpostor._tmpVecs[2];
  82298. boneAxis.x = 0;
  82299. boneAxis.y = 1;
  82300. boneAxis.z = 0;
  82301. }
  82302. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82303. bone.getAbsolutePositionToRef(boneMesh, pos);
  82304. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82305. distToJoint = jointPivot.length();
  82306. }
  82307. if (distToJoint !== undefined && distToJoint !== null) {
  82308. pos.x += boneDir.x * distToJoint;
  82309. pos.y += boneDir.y * distToJoint;
  82310. pos.z += boneDir.z * distToJoint;
  82311. }
  82312. mesh.setAbsolutePosition(pos);
  82313. };
  82314. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82315. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82316. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82317. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82318. //Impostor types
  82319. PhysicsImpostor.NoImpostor = 0;
  82320. PhysicsImpostor.SphereImpostor = 1;
  82321. PhysicsImpostor.BoxImpostor = 2;
  82322. PhysicsImpostor.PlaneImpostor = 3;
  82323. PhysicsImpostor.MeshImpostor = 4;
  82324. PhysicsImpostor.CylinderImpostor = 7;
  82325. PhysicsImpostor.ParticleImpostor = 8;
  82326. PhysicsImpostor.HeightmapImpostor = 9;
  82327. return PhysicsImpostor;
  82328. }());
  82329. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82330. })(BABYLON || (BABYLON = {}));
  82331. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82332. var BABYLON;
  82333. (function (BABYLON) {
  82334. var PhysicsEngine = /** @class */ (function () {
  82335. function PhysicsEngine(gravity, _physicsPlugin) {
  82336. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82337. this._physicsPlugin = _physicsPlugin;
  82338. //new methods and parameters
  82339. this._impostors = [];
  82340. this._joints = [];
  82341. if (!this._physicsPlugin.isSupported()) {
  82342. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82343. + "Please make sure it is included.");
  82344. }
  82345. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82346. this.setGravity(gravity);
  82347. this.setTimeStep();
  82348. }
  82349. PhysicsEngine.prototype.setGravity = function (gravity) {
  82350. this.gravity = gravity;
  82351. this._physicsPlugin.setGravity(this.gravity);
  82352. };
  82353. /**
  82354. * Set the time step of the physics engine.
  82355. * default is 1/60.
  82356. * To slow it down, enter 1/600 for example.
  82357. * To speed it up, 1/30
  82358. * @param {number} newTimeStep the new timestep to apply to this world.
  82359. */
  82360. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82361. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82362. this._physicsPlugin.setTimeStep(newTimeStep);
  82363. };
  82364. /**
  82365. * Get the time step of the physics engine.
  82366. */
  82367. PhysicsEngine.prototype.getTimeStep = function () {
  82368. return this._physicsPlugin.getTimeStep();
  82369. };
  82370. PhysicsEngine.prototype.dispose = function () {
  82371. this._impostors.forEach(function (impostor) {
  82372. impostor.dispose();
  82373. });
  82374. this._physicsPlugin.dispose();
  82375. };
  82376. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82377. return this._physicsPlugin.name;
  82378. };
  82379. /**
  82380. * Adding a new impostor for the impostor tracking.
  82381. * This will be done by the impostor itself.
  82382. * @param {PhysicsImpostor} impostor the impostor to add
  82383. */
  82384. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82385. impostor.uniqueId = this._impostors.push(impostor);
  82386. //if no parent, generate the body
  82387. if (!impostor.parent) {
  82388. this._physicsPlugin.generatePhysicsBody(impostor);
  82389. }
  82390. };
  82391. /**
  82392. * Remove an impostor from the engine.
  82393. * This impostor and its mesh will not longer be updated by the physics engine.
  82394. * @param {PhysicsImpostor} impostor the impostor to remove
  82395. */
  82396. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82397. var index = this._impostors.indexOf(impostor);
  82398. if (index > -1) {
  82399. var removed = this._impostors.splice(index, 1);
  82400. //Is it needed?
  82401. if (removed.length) {
  82402. //this will also remove it from the world.
  82403. removed[0].physicsBody = null;
  82404. }
  82405. }
  82406. };
  82407. /**
  82408. * Add a joint to the physics engine
  82409. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82410. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82411. * @param {PhysicsJoint} the joint that will connect both impostors.
  82412. */
  82413. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82414. var impostorJoint = {
  82415. mainImpostor: mainImpostor,
  82416. connectedImpostor: connectedImpostor,
  82417. joint: joint
  82418. };
  82419. joint.physicsPlugin = this._physicsPlugin;
  82420. this._joints.push(impostorJoint);
  82421. this._physicsPlugin.generateJoint(impostorJoint);
  82422. };
  82423. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82424. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82425. return (impostorJoint.connectedImpostor === connectedImpostor
  82426. && impostorJoint.joint === joint
  82427. && impostorJoint.mainImpostor === mainImpostor);
  82428. });
  82429. if (matchingJoints.length) {
  82430. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82431. //TODO remove it from the list as well
  82432. }
  82433. };
  82434. /**
  82435. * Called by the scene. no need to call it.
  82436. */
  82437. PhysicsEngine.prototype._step = function (delta) {
  82438. var _this = this;
  82439. //check if any mesh has no body / requires an update
  82440. this._impostors.forEach(function (impostor) {
  82441. if (impostor.isBodyInitRequired()) {
  82442. _this._physicsPlugin.generatePhysicsBody(impostor);
  82443. }
  82444. });
  82445. if (delta > 0.1) {
  82446. delta = 0.1;
  82447. }
  82448. else if (delta <= 0) {
  82449. delta = 1.0 / 60.0;
  82450. }
  82451. this._physicsPlugin.executeStep(delta, this._impostors);
  82452. };
  82453. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82454. return this._physicsPlugin;
  82455. };
  82456. PhysicsEngine.prototype.getImpostors = function () {
  82457. return this._impostors;
  82458. };
  82459. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82460. for (var i = 0; i < this._impostors.length; ++i) {
  82461. if (this._impostors[i].object === object) {
  82462. return this._impostors[i];
  82463. }
  82464. }
  82465. return null;
  82466. };
  82467. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82468. for (var i = 0; i < this._impostors.length; ++i) {
  82469. if (this._impostors[i].physicsBody === body) {
  82470. return this._impostors[i];
  82471. }
  82472. }
  82473. return null;
  82474. };
  82475. // Statics
  82476. PhysicsEngine.Epsilon = 0.001;
  82477. return PhysicsEngine;
  82478. }());
  82479. BABYLON.PhysicsEngine = PhysicsEngine;
  82480. })(BABYLON || (BABYLON = {}));
  82481. //# sourceMappingURL=babylon.physicsEngine.js.map
  82482. var BABYLON;
  82483. (function (BABYLON) {
  82484. var PhysicsHelper = /** @class */ (function () {
  82485. function PhysicsHelper(scene) {
  82486. this._scene = scene;
  82487. this._physicsEngine = this._scene.getPhysicsEngine();
  82488. if (!this._physicsEngine) {
  82489. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  82490. }
  82491. }
  82492. /**
  82493. * @param {Vector3} origin the origin of the explosion
  82494. * @param {number} radius the explosion radius
  82495. * @param {number} strength the explosion strength
  82496. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82497. */
  82498. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  82499. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82500. if (!this._physicsEngine) {
  82501. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  82502. return null;
  82503. }
  82504. var impostors = this._physicsEngine.getImpostors();
  82505. if (impostors.length === 0) {
  82506. return null;
  82507. }
  82508. var event = new PhysicsRadialExplosionEvent(this._scene);
  82509. impostors.forEach(function (impostor) {
  82510. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82511. if (!impostorForceAndContactPoint) {
  82512. return;
  82513. }
  82514. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82515. });
  82516. event.dispose(false);
  82517. return event;
  82518. };
  82519. /**
  82520. * @param {Vector3} origin the origin of the explosion
  82521. * @param {number} radius the explosion radius
  82522. * @param {number} strength the explosion strength
  82523. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82524. */
  82525. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82526. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82527. if (!this._physicsEngine) {
  82528. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82529. return null;
  82530. }
  82531. var impostors = this._physicsEngine.getImpostors();
  82532. if (impostors.length === 0) {
  82533. return null;
  82534. }
  82535. var event = new PhysicsRadialExplosionEvent(this._scene);
  82536. impostors.forEach(function (impostor) {
  82537. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82538. if (!impostorForceAndContactPoint) {
  82539. return;
  82540. }
  82541. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82542. });
  82543. event.dispose(false);
  82544. return event;
  82545. };
  82546. /**
  82547. * @param {Vector3} origin the origin of the explosion
  82548. * @param {number} radius the explosion radius
  82549. * @param {number} strength the explosion strength
  82550. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82551. */
  82552. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82553. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82554. if (!this._physicsEngine) {
  82555. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82556. return null;
  82557. }
  82558. var impostors = this._physicsEngine.getImpostors();
  82559. if (impostors.length === 0) {
  82560. return null;
  82561. }
  82562. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82563. event.dispose(false);
  82564. return event;
  82565. };
  82566. /**
  82567. * @param {Vector3} origin the origin of the updraft
  82568. * @param {number} radius the radius of the updraft
  82569. * @param {number} strength the strength of the updraft
  82570. * @param {number} height the height of the updraft
  82571. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82572. */
  82573. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82574. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82575. if (!this._physicsEngine) {
  82576. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82577. return null;
  82578. }
  82579. if (this._physicsEngine.getImpostors().length === 0) {
  82580. return null;
  82581. }
  82582. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82583. event.dispose(false);
  82584. return event;
  82585. };
  82586. /**
  82587. * @param {Vector3} origin the of the vortex
  82588. * @param {number} radius the radius of the vortex
  82589. * @param {number} strength the strength of the vortex
  82590. * @param {number} height the height of the vortex
  82591. */
  82592. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82593. if (!this._physicsEngine) {
  82594. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82595. return null;
  82596. }
  82597. if (this._physicsEngine.getImpostors().length === 0) {
  82598. return null;
  82599. }
  82600. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82601. event.dispose(false);
  82602. return event;
  82603. };
  82604. return PhysicsHelper;
  82605. }());
  82606. BABYLON.PhysicsHelper = PhysicsHelper;
  82607. /***** Radial explosion *****/
  82608. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82609. function PhysicsRadialExplosionEvent(scene) {
  82610. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82611. this._rays = [];
  82612. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82613. this._scene = scene;
  82614. }
  82615. /**
  82616. * Returns the data related to the radial explosion event (sphere & rays).
  82617. * @returns {PhysicsRadialExplosionEventData}
  82618. */
  82619. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82620. this._dataFetched = true;
  82621. return {
  82622. sphere: this._sphere,
  82623. rays: this._rays,
  82624. };
  82625. };
  82626. /**
  82627. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82628. * @param impostor
  82629. * @param {Vector3} origin the origin of the explosion
  82630. * @param {number} radius the explosion radius
  82631. * @param {number} strength the explosion strength
  82632. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82633. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82634. */
  82635. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82636. if (impostor.mass === 0) {
  82637. return null;
  82638. }
  82639. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82640. return null;
  82641. }
  82642. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82643. return null;
  82644. }
  82645. var impostorObjectCenter = impostor.getObjectCenter();
  82646. var direction = impostorObjectCenter.subtract(origin);
  82647. var ray = new BABYLON.Ray(origin, direction, radius);
  82648. this._rays.push(ray);
  82649. var hit = ray.intersectsMesh(impostor.object);
  82650. var contactPoint = hit.pickedPoint;
  82651. if (!contactPoint) {
  82652. return null;
  82653. }
  82654. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82655. if (distanceFromOrigin > radius) {
  82656. return null;
  82657. }
  82658. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82659. ? strength
  82660. : strength * (1 - (distanceFromOrigin / radius));
  82661. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82662. return { force: force, contactPoint: contactPoint };
  82663. };
  82664. /**
  82665. * Disposes the sphere.
  82666. * @param {bolean} force
  82667. */
  82668. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82669. var _this = this;
  82670. if (force === void 0) { force = true; }
  82671. if (force) {
  82672. this._sphere.dispose();
  82673. }
  82674. else {
  82675. setTimeout(function () {
  82676. if (!_this._dataFetched) {
  82677. _this._sphere.dispose();
  82678. }
  82679. }, 0);
  82680. }
  82681. };
  82682. /*** Helpers ***/
  82683. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82684. if (!this._sphere) {
  82685. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82686. this._sphere.isVisible = false;
  82687. }
  82688. };
  82689. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82690. var impostorObject = impostor.object;
  82691. this._prepareSphere();
  82692. this._sphere.position = origin;
  82693. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82694. this._sphere._updateBoundingInfo();
  82695. this._sphere.computeWorldMatrix(true);
  82696. return this._sphere.intersectsMesh(impostorObject, true);
  82697. };
  82698. return PhysicsRadialExplosionEvent;
  82699. }());
  82700. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82701. /***** Gravitational Field *****/
  82702. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82703. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82704. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82705. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82706. this._physicsHelper = physicsHelper;
  82707. this._scene = scene;
  82708. this._origin = origin;
  82709. this._radius = radius;
  82710. this._strength = strength;
  82711. this._falloff = falloff;
  82712. this._tickCallback = this._tick.bind(this);
  82713. }
  82714. /**
  82715. * Returns the data related to the gravitational field event (sphere).
  82716. * @returns {PhysicsGravitationalFieldEventData}
  82717. */
  82718. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82719. this._dataFetched = true;
  82720. return {
  82721. sphere: this._sphere,
  82722. };
  82723. };
  82724. /**
  82725. * Enables the gravitational field.
  82726. */
  82727. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82728. this._tickCallback.call(this);
  82729. this._scene.registerBeforeRender(this._tickCallback);
  82730. };
  82731. /**
  82732. * Disables the gravitational field.
  82733. */
  82734. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82735. this._scene.unregisterBeforeRender(this._tickCallback);
  82736. };
  82737. /**
  82738. * Disposes the sphere.
  82739. * @param {bolean} force
  82740. */
  82741. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82742. var _this = this;
  82743. if (force === void 0) { force = true; }
  82744. if (force) {
  82745. this._sphere.dispose();
  82746. }
  82747. else {
  82748. setTimeout(function () {
  82749. if (!_this._dataFetched) {
  82750. _this._sphere.dispose();
  82751. }
  82752. }, 0);
  82753. }
  82754. };
  82755. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82756. // Since the params won't change, we fetch the event only once
  82757. if (this._sphere) {
  82758. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82759. }
  82760. else {
  82761. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82762. if (radialExplosionEvent) {
  82763. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82764. }
  82765. }
  82766. };
  82767. return PhysicsGravitationalFieldEvent;
  82768. }());
  82769. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82770. /***** Updraft *****/
  82771. var PhysicsUpdraftEvent = /** @class */ (function () {
  82772. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82773. this._scene = _scene;
  82774. this._origin = _origin;
  82775. this._radius = _radius;
  82776. this._strength = _strength;
  82777. this._height = _height;
  82778. this._updraftMode = _updraftMode;
  82779. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82780. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82781. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82782. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82783. this._physicsEngine = this._scene.getPhysicsEngine();
  82784. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82785. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82786. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82787. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82788. }
  82789. this._tickCallback = this._tick.bind(this);
  82790. }
  82791. /**
  82792. * Returns the data related to the updraft event (cylinder).
  82793. * @returns {PhysicsUpdraftEventData}
  82794. */
  82795. PhysicsUpdraftEvent.prototype.getData = function () {
  82796. this._dataFetched = true;
  82797. return {
  82798. cylinder: this._cylinder,
  82799. };
  82800. };
  82801. /**
  82802. * Enables the updraft.
  82803. */
  82804. PhysicsUpdraftEvent.prototype.enable = function () {
  82805. this._tickCallback.call(this);
  82806. this._scene.registerBeforeRender(this._tickCallback);
  82807. };
  82808. /**
  82809. * Disables the cortex.
  82810. */
  82811. PhysicsUpdraftEvent.prototype.disable = function () {
  82812. this._scene.unregisterBeforeRender(this._tickCallback);
  82813. };
  82814. /**
  82815. * Disposes the sphere.
  82816. * @param {bolean} force
  82817. */
  82818. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82819. var _this = this;
  82820. if (force === void 0) { force = true; }
  82821. if (force) {
  82822. this._cylinder.dispose();
  82823. }
  82824. else {
  82825. setTimeout(function () {
  82826. if (!_this._dataFetched) {
  82827. _this._cylinder.dispose();
  82828. }
  82829. }, 0);
  82830. }
  82831. };
  82832. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82833. if (impostor.mass === 0) {
  82834. return null;
  82835. }
  82836. if (!this._intersectsWithCylinder(impostor)) {
  82837. return null;
  82838. }
  82839. var impostorObjectCenter = impostor.getObjectCenter();
  82840. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82841. var direction = this._originDirection;
  82842. }
  82843. else {
  82844. var direction = impostorObjectCenter.subtract(this._originTop);
  82845. }
  82846. var multiplier = this._strength * -1;
  82847. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82848. return { force: force, contactPoint: impostorObjectCenter };
  82849. };
  82850. PhysicsUpdraftEvent.prototype._tick = function () {
  82851. var _this = this;
  82852. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82853. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82854. if (!impostorForceAndContactPoint) {
  82855. return;
  82856. }
  82857. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82858. });
  82859. };
  82860. /*** Helpers ***/
  82861. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  82862. if (!this._cylinder) {
  82863. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  82864. height: this._height,
  82865. diameter: this._radius * 2,
  82866. }, this._scene);
  82867. this._cylinder.isVisible = false;
  82868. }
  82869. };
  82870. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  82871. var impostorObject = impostor.object;
  82872. this._prepareCylinder();
  82873. this._cylinder.position = this._cylinderPosition;
  82874. return this._cylinder.intersectsMesh(impostorObject, true);
  82875. };
  82876. return PhysicsUpdraftEvent;
  82877. }());
  82878. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  82879. /***** Vortex *****/
  82880. var PhysicsVortexEvent = /** @class */ (function () {
  82881. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  82882. this._scene = _scene;
  82883. this._origin = _origin;
  82884. this._radius = _radius;
  82885. this._strength = _strength;
  82886. this._height = _height;
  82887. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82888. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  82889. this._updraftMultiplier = 0.02;
  82890. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82891. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82892. this._physicsEngine = this._scene.getPhysicsEngine();
  82893. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82894. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82895. this._tickCallback = this._tick.bind(this);
  82896. }
  82897. /**
  82898. * Returns the data related to the vortex event (cylinder).
  82899. * @returns {PhysicsVortexEventData}
  82900. */
  82901. PhysicsVortexEvent.prototype.getData = function () {
  82902. this._dataFetched = true;
  82903. return {
  82904. cylinder: this._cylinder,
  82905. };
  82906. };
  82907. /**
  82908. * Enables the vortex.
  82909. */
  82910. PhysicsVortexEvent.prototype.enable = function () {
  82911. this._tickCallback.call(this);
  82912. this._scene.registerBeforeRender(this._tickCallback);
  82913. };
  82914. /**
  82915. * Disables the cortex.
  82916. */
  82917. PhysicsVortexEvent.prototype.disable = function () {
  82918. this._scene.unregisterBeforeRender(this._tickCallback);
  82919. };
  82920. /**
  82921. * Disposes the sphere.
  82922. * @param {bolean} force
  82923. */
  82924. PhysicsVortexEvent.prototype.dispose = function (force) {
  82925. var _this = this;
  82926. if (force === void 0) { force = true; }
  82927. if (force) {
  82928. this._cylinder.dispose();
  82929. }
  82930. else {
  82931. setTimeout(function () {
  82932. if (!_this._dataFetched) {
  82933. _this._cylinder.dispose();
  82934. }
  82935. }, 0);
  82936. }
  82937. };
  82938. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82939. if (impostor.mass === 0) {
  82940. return null;
  82941. }
  82942. if (!this._intersectsWithCylinder(impostor)) {
  82943. return null;
  82944. }
  82945. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82946. return null;
  82947. }
  82948. var impostorObjectCenter = impostor.getObjectCenter();
  82949. 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)
  82950. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  82951. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  82952. var hit = ray.intersectsMesh(impostor.object);
  82953. var contactPoint = hit.pickedPoint;
  82954. if (!contactPoint) {
  82955. return null;
  82956. }
  82957. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  82958. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  82959. var directionToOrigin = contactPoint.normalize();
  82960. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82961. directionToOrigin = directionToOrigin.negate();
  82962. }
  82963. // TODO: find a more physically based solution
  82964. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82965. var forceX = directionToOrigin.x * this._strength / 8;
  82966. var forceY = directionToOrigin.y * this._updraftMultiplier;
  82967. var forceZ = directionToOrigin.z * this._strength / 8;
  82968. }
  82969. else {
  82970. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  82971. var forceY = this._originTop.y * this._updraftMultiplier;
  82972. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  82973. }
  82974. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  82975. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  82976. return { force: force, contactPoint: impostorObjectCenter };
  82977. };
  82978. PhysicsVortexEvent.prototype._tick = function () {
  82979. var _this = this;
  82980. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82981. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82982. if (!impostorForceAndContactPoint) {
  82983. return;
  82984. }
  82985. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82986. });
  82987. };
  82988. /*** Helpers ***/
  82989. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  82990. if (!this._cylinder) {
  82991. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  82992. height: this._height,
  82993. diameter: this._radius * 2,
  82994. }, this._scene);
  82995. this._cylinder.isVisible = false;
  82996. }
  82997. };
  82998. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  82999. var impostorObject = impostor.object;
  83000. this._prepareCylinder();
  83001. this._cylinder.position = this._cylinderPosition;
  83002. return this._cylinder.intersectsMesh(impostorObject, true);
  83003. };
  83004. return PhysicsVortexEvent;
  83005. }());
  83006. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  83007. /***** Enums *****/
  83008. /**
  83009. * The strenght of the force in correspondence to the distance of the affected object
  83010. */
  83011. var PhysicsRadialImpulseFalloff;
  83012. (function (PhysicsRadialImpulseFalloff) {
  83013. /** Defines that impulse is constant in strength across it's whole radius */
  83014. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  83015. /** DEfines that impulse gets weaker if it's further from the origin */
  83016. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  83017. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  83018. /**
  83019. * The strenght of the force in correspondence to the distance of the affected object
  83020. */
  83021. var PhysicsUpdraftMode;
  83022. (function (PhysicsUpdraftMode) {
  83023. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  83024. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  83025. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  83026. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  83027. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  83028. })(BABYLON || (BABYLON = {}));
  83029. //# sourceMappingURL=babylon.physicsHelper.js.map
  83030. var BABYLON;
  83031. (function (BABYLON) {
  83032. var CannonJSPlugin = /** @class */ (function () {
  83033. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  83034. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  83035. if (iterations === void 0) { iterations = 10; }
  83036. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  83037. this.name = "CannonJSPlugin";
  83038. this._physicsMaterials = new Array();
  83039. this._fixedTimeStep = 1 / 60;
  83040. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  83041. this.BJSCANNON = CANNON;
  83042. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  83043. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  83044. this._tmpPosition = BABYLON.Vector3.Zero();
  83045. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  83046. this._tmpUnityRotation = new BABYLON.Quaternion();
  83047. if (!this.isSupported()) {
  83048. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  83049. return;
  83050. }
  83051. this._extendNamespace();
  83052. this.world = new this.BJSCANNON.World();
  83053. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  83054. this.world.solver.iterations = iterations;
  83055. }
  83056. CannonJSPlugin.prototype.setGravity = function (gravity) {
  83057. this.world.gravity.copy(gravity);
  83058. };
  83059. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  83060. this._fixedTimeStep = timeStep;
  83061. };
  83062. CannonJSPlugin.prototype.getTimeStep = function () {
  83063. return this._fixedTimeStep;
  83064. };
  83065. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  83066. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  83067. };
  83068. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83069. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83070. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83071. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  83072. };
  83073. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83074. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83075. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83076. impostor.physicsBody.applyForce(impulse, worldPoint);
  83077. };
  83078. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83079. //parent-child relationship. Does this impostor has a parent impostor?
  83080. if (impostor.parent) {
  83081. if (impostor.physicsBody) {
  83082. this.removePhysicsBody(impostor);
  83083. //TODO is that needed?
  83084. impostor.forceUpdate();
  83085. }
  83086. return;
  83087. }
  83088. //should a new body be created for this impostor?
  83089. if (impostor.isBodyInitRequired()) {
  83090. var shape = this._createShape(impostor);
  83091. //unregister events, if body is being changed
  83092. var oldBody = impostor.physicsBody;
  83093. if (oldBody) {
  83094. this.removePhysicsBody(impostor);
  83095. }
  83096. //create the body and material
  83097. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83098. var bodyCreationObject = {
  83099. mass: impostor.getParam("mass"),
  83100. material: material
  83101. };
  83102. // A simple extend, in case native options were used.
  83103. var nativeOptions = impostor.getParam("nativeOptions");
  83104. for (var key in nativeOptions) {
  83105. if (nativeOptions.hasOwnProperty(key)) {
  83106. bodyCreationObject[key] = nativeOptions[key];
  83107. }
  83108. }
  83109. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83110. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83111. this.world.addEventListener("preStep", impostor.beforeStep);
  83112. this.world.addEventListener("postStep", impostor.afterStep);
  83113. impostor.physicsBody.addShape(shape);
  83114. this.world.add(impostor.physicsBody);
  83115. //try to keep the body moving in the right direction by taking old properties.
  83116. //Should be tested!
  83117. if (oldBody) {
  83118. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83119. impostor.physicsBody[param].copy(oldBody[param]);
  83120. });
  83121. }
  83122. this._processChildMeshes(impostor);
  83123. }
  83124. //now update the body's transformation
  83125. this._updatePhysicsBodyTransformation(impostor);
  83126. };
  83127. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83128. var _this = this;
  83129. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83130. var currentRotation = mainImpostor.object.rotationQuaternion;
  83131. if (meshChildren.length) {
  83132. var processMesh = function (localPosition, mesh) {
  83133. if (!currentRotation || !mesh.rotationQuaternion) {
  83134. return;
  83135. }
  83136. var childImpostor = mesh.getPhysicsImpostor();
  83137. if (childImpostor) {
  83138. var parent = childImpostor.parent;
  83139. if (parent !== mainImpostor) {
  83140. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83141. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83142. if (childImpostor.physicsBody) {
  83143. _this.removePhysicsBody(childImpostor);
  83144. childImpostor.physicsBody = null;
  83145. }
  83146. childImpostor.parent = mainImpostor;
  83147. childImpostor.resetUpdateFlags();
  83148. 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));
  83149. //Add the mass of the children.
  83150. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83151. }
  83152. }
  83153. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83154. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83155. };
  83156. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83157. }
  83158. };
  83159. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83160. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83161. this.world.removeEventListener("preStep", impostor.beforeStep);
  83162. this.world.removeEventListener("postStep", impostor.afterStep);
  83163. this.world.remove(impostor.physicsBody);
  83164. };
  83165. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83166. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83167. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83168. if (!mainBody || !connectedBody) {
  83169. return;
  83170. }
  83171. var constraint;
  83172. var jointData = impostorJoint.joint.jointData;
  83173. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83174. var constraintData = {
  83175. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83176. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83177. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83178. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83179. maxForce: jointData.nativeParams.maxForce,
  83180. collideConnected: !!jointData.collision
  83181. };
  83182. switch (impostorJoint.joint.type) {
  83183. case BABYLON.PhysicsJoint.HingeJoint:
  83184. case BABYLON.PhysicsJoint.Hinge2Joint:
  83185. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83186. break;
  83187. case BABYLON.PhysicsJoint.DistanceJoint:
  83188. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83189. break;
  83190. case BABYLON.PhysicsJoint.SpringJoint:
  83191. var springData = jointData;
  83192. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83193. restLength: springData.length,
  83194. stiffness: springData.stiffness,
  83195. damping: springData.damping,
  83196. localAnchorA: constraintData.pivotA,
  83197. localAnchorB: constraintData.pivotB
  83198. });
  83199. break;
  83200. case BABYLON.PhysicsJoint.LockJoint:
  83201. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83202. break;
  83203. case BABYLON.PhysicsJoint.PointToPointJoint:
  83204. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83205. default:
  83206. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83207. break;
  83208. }
  83209. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83210. constraint.collideConnected = !!jointData.collision;
  83211. impostorJoint.joint.physicsJoint = constraint;
  83212. //don't add spring as constraint, as it is not one.
  83213. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83214. this.world.addConstraint(constraint);
  83215. }
  83216. else {
  83217. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83218. constraint.applyForce();
  83219. });
  83220. }
  83221. };
  83222. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83223. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83224. };
  83225. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83226. var index;
  83227. var mat;
  83228. for (index = 0; index < this._physicsMaterials.length; index++) {
  83229. mat = this._physicsMaterials[index];
  83230. if (mat.friction === friction && mat.restitution === restitution) {
  83231. return mat;
  83232. }
  83233. }
  83234. var currentMat = new this.BJSCANNON.Material(name);
  83235. currentMat.friction = friction;
  83236. currentMat.restitution = restitution;
  83237. this._physicsMaterials.push(currentMat);
  83238. return currentMat;
  83239. };
  83240. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83241. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83242. };
  83243. CannonJSPlugin.prototype._createShape = function (impostor) {
  83244. var object = impostor.object;
  83245. var returnValue;
  83246. var extendSize = impostor.getObjectExtendSize();
  83247. switch (impostor.type) {
  83248. case BABYLON.PhysicsImpostor.SphereImpostor:
  83249. var radiusX = extendSize.x;
  83250. var radiusY = extendSize.y;
  83251. var radiusZ = extendSize.z;
  83252. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83253. break;
  83254. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83255. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83256. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83257. break;
  83258. case BABYLON.PhysicsImpostor.BoxImpostor:
  83259. var box = extendSize.scale(0.5);
  83260. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83261. break;
  83262. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83263. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83264. returnValue = new this.BJSCANNON.Plane();
  83265. break;
  83266. case BABYLON.PhysicsImpostor.MeshImpostor:
  83267. // should transform the vertex data to world coordinates!!
  83268. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83269. var rawFaces = object.getIndices ? object.getIndices() : [];
  83270. if (!rawVerts)
  83271. return;
  83272. // get only scale! so the object could transform correctly.
  83273. var oldPosition = object.position.clone();
  83274. var oldRotation = object.rotation && object.rotation.clone();
  83275. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83276. object.position.copyFromFloats(0, 0, 0);
  83277. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83278. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83279. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83280. var transform = object.computeWorldMatrix(true);
  83281. // convert rawVerts to object space
  83282. var temp = new Array();
  83283. var index;
  83284. for (index = 0; index < rawVerts.length; index += 3) {
  83285. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83286. }
  83287. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83288. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83289. //now set back the transformation!
  83290. object.position.copyFrom(oldPosition);
  83291. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83292. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83293. break;
  83294. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83295. var oldPosition2 = object.position.clone();
  83296. var oldRotation2 = object.rotation && object.rotation.clone();
  83297. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83298. object.position.copyFromFloats(0, 0, 0);
  83299. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83300. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83301. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83302. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83303. returnValue = this._createHeightmap(object);
  83304. object.position.copyFrom(oldPosition2);
  83305. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83306. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83307. object.computeWorldMatrix(true);
  83308. break;
  83309. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83310. returnValue = new this.BJSCANNON.Particle();
  83311. break;
  83312. }
  83313. return returnValue;
  83314. };
  83315. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83316. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83317. var transform = object.computeWorldMatrix(true);
  83318. // convert rawVerts to object space
  83319. var temp = new Array();
  83320. var index;
  83321. for (index = 0; index < pos.length; index += 3) {
  83322. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83323. }
  83324. pos = temp;
  83325. var matrix = new Array();
  83326. //For now pointDepth will not be used and will be automatically calculated.
  83327. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83328. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83329. var boundingInfo = object.getBoundingInfo();
  83330. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83331. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83332. var elementSize = dim * 2 / arraySize;
  83333. for (var i = 0; i < pos.length; i = i + 3) {
  83334. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83335. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83336. var y = -pos[i + 2] + minY;
  83337. if (!matrix[x]) {
  83338. matrix[x] = [];
  83339. }
  83340. if (!matrix[x][z]) {
  83341. matrix[x][z] = y;
  83342. }
  83343. matrix[x][z] = Math.max(y, matrix[x][z]);
  83344. }
  83345. for (var x = 0; x <= arraySize; ++x) {
  83346. if (!matrix[x]) {
  83347. var loc = 1;
  83348. while (!matrix[(x + loc) % arraySize]) {
  83349. loc++;
  83350. }
  83351. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83352. //console.log("missing x", x);
  83353. }
  83354. for (var z = 0; z <= arraySize; ++z) {
  83355. if (!matrix[x][z]) {
  83356. var loc = 1;
  83357. var newValue;
  83358. while (newValue === undefined) {
  83359. newValue = matrix[x][(z + loc++) % arraySize];
  83360. }
  83361. matrix[x][z] = newValue;
  83362. }
  83363. }
  83364. }
  83365. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83366. elementSize: elementSize
  83367. });
  83368. //For future reference, needed for body transformation
  83369. shape.minY = minY;
  83370. return shape;
  83371. };
  83372. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83373. var object = impostor.object;
  83374. //make sure it is updated...
  83375. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83376. // The delta between the mesh position and the mesh bounding box center
  83377. var bInfo = object.getBoundingInfo();
  83378. if (!bInfo)
  83379. return;
  83380. var center = impostor.getObjectCenter();
  83381. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83382. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83383. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83384. this._tmpPosition.copyFrom(center);
  83385. var quaternion = object.rotationQuaternion;
  83386. if (!quaternion) {
  83387. return;
  83388. }
  83389. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83390. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83391. //-90 DEG in X, precalculated
  83392. quaternion = quaternion.multiply(this._minus90X);
  83393. //Invert! (Precalculated, 90 deg in X)
  83394. //No need to clone. this will never change.
  83395. impostor.setDeltaRotation(this._plus90X);
  83396. }
  83397. //If it is a heightfield, if should be centered.
  83398. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83399. var mesh = object;
  83400. var boundingInfo = mesh.getBoundingInfo();
  83401. //calculate the correct body position:
  83402. var rotationQuaternion = mesh.rotationQuaternion;
  83403. mesh.rotationQuaternion = this._tmpUnityRotation;
  83404. mesh.computeWorldMatrix(true);
  83405. //get original center with no rotation
  83406. var c = center.clone();
  83407. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83408. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83409. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83410. mesh.setPreTransformMatrix(p);
  83411. mesh.computeWorldMatrix(true);
  83412. //calculate the translation
  83413. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83414. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83415. //add it inverted to the delta
  83416. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83417. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83418. //rotation is back
  83419. mesh.rotationQuaternion = rotationQuaternion;
  83420. mesh.setPreTransformMatrix(oldPivot);
  83421. mesh.computeWorldMatrix(true);
  83422. }
  83423. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83424. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83425. //this._tmpPosition.copyFrom(object.position);
  83426. }
  83427. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83428. //Now update the impostor object
  83429. impostor.physicsBody.position.copy(this._tmpPosition);
  83430. impostor.physicsBody.quaternion.copy(quaternion);
  83431. };
  83432. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83433. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83434. if (impostor.object.rotationQuaternion) {
  83435. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83436. }
  83437. };
  83438. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83439. impostor.physicsBody.position.copy(newPosition);
  83440. impostor.physicsBody.quaternion.copy(newRotation);
  83441. };
  83442. CannonJSPlugin.prototype.isSupported = function () {
  83443. return this.BJSCANNON !== undefined;
  83444. };
  83445. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83446. impostor.physicsBody.velocity.copy(velocity);
  83447. };
  83448. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83449. impostor.physicsBody.angularVelocity.copy(velocity);
  83450. };
  83451. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83452. var v = impostor.physicsBody.velocity;
  83453. if (!v) {
  83454. return null;
  83455. }
  83456. return new BABYLON.Vector3(v.x, v.y, v.z);
  83457. };
  83458. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83459. var v = impostor.physicsBody.angularVelocity;
  83460. if (!v) {
  83461. return null;
  83462. }
  83463. return new BABYLON.Vector3(v.x, v.y, v.z);
  83464. };
  83465. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83466. impostor.physicsBody.mass = mass;
  83467. impostor.physicsBody.updateMassProperties();
  83468. };
  83469. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83470. return impostor.physicsBody.mass;
  83471. };
  83472. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83473. return impostor.physicsBody.material.friction;
  83474. };
  83475. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83476. impostor.physicsBody.material.friction = friction;
  83477. };
  83478. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83479. return impostor.physicsBody.material.restitution;
  83480. };
  83481. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83482. impostor.physicsBody.material.restitution = restitution;
  83483. };
  83484. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  83485. impostor.physicsBody.sleep();
  83486. };
  83487. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  83488. impostor.physicsBody.wakeUp();
  83489. };
  83490. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83491. joint.physicsJoint.distance = maxDistance;
  83492. };
  83493. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83494. // if (!motorIndex) {
  83495. // joint.physicsJoint.enableMotor();
  83496. // }
  83497. // }
  83498. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83499. // if (!motorIndex) {
  83500. // joint.physicsJoint.disableMotor();
  83501. // }
  83502. // }
  83503. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83504. if (!motorIndex) {
  83505. joint.physicsJoint.enableMotor();
  83506. joint.physicsJoint.setMotorSpeed(speed);
  83507. if (maxForce) {
  83508. this.setLimit(joint, maxForce);
  83509. }
  83510. }
  83511. };
  83512. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83513. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83514. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83515. };
  83516. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83517. var body = impostor.physicsBody;
  83518. mesh.position.x = body.position.x;
  83519. mesh.position.y = body.position.y;
  83520. mesh.position.z = body.position.z;
  83521. if (mesh.rotationQuaternion) {
  83522. mesh.rotationQuaternion.x = body.quaternion.x;
  83523. mesh.rotationQuaternion.y = body.quaternion.y;
  83524. mesh.rotationQuaternion.z = body.quaternion.z;
  83525. mesh.rotationQuaternion.w = body.quaternion.w;
  83526. }
  83527. };
  83528. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83529. var shape = impostor.physicsBody.shapes[0];
  83530. return shape.boundingSphereRadius;
  83531. };
  83532. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83533. var shape = impostor.physicsBody.shapes[0];
  83534. result.x = shape.halfExtents.x * 2;
  83535. result.y = shape.halfExtents.y * 2;
  83536. result.z = shape.halfExtents.z * 2;
  83537. };
  83538. CannonJSPlugin.prototype.dispose = function () {
  83539. };
  83540. CannonJSPlugin.prototype._extendNamespace = function () {
  83541. //this will force cannon to execute at least one step when using interpolation
  83542. var step_tmp1 = new this.BJSCANNON.Vec3();
  83543. var Engine = this.BJSCANNON;
  83544. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83545. maxSubSteps = maxSubSteps || 10;
  83546. timeSinceLastCalled = timeSinceLastCalled || 0;
  83547. if (timeSinceLastCalled === 0) {
  83548. this.internalStep(dt);
  83549. this.time += dt;
  83550. }
  83551. else {
  83552. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83553. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83554. var t0 = performance.now();
  83555. for (var i = 0; i !== internalSteps; i++) {
  83556. this.internalStep(dt);
  83557. if (performance.now() - t0 > dt * 1000) {
  83558. break;
  83559. }
  83560. }
  83561. this.time += timeSinceLastCalled;
  83562. var h = this.time % dt;
  83563. var h_div_dt = h / dt;
  83564. var interpvelo = step_tmp1;
  83565. var bodies = this.bodies;
  83566. for (var j = 0; j !== bodies.length; j++) {
  83567. var b = bodies[j];
  83568. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83569. b.position.vsub(b.previousPosition, interpvelo);
  83570. interpvelo.scale(h_div_dt, interpvelo);
  83571. b.position.vadd(interpvelo, b.interpolatedPosition);
  83572. }
  83573. else {
  83574. b.interpolatedPosition.copy(b.position);
  83575. b.interpolatedQuaternion.copy(b.quaternion);
  83576. }
  83577. }
  83578. }
  83579. };
  83580. };
  83581. return CannonJSPlugin;
  83582. }());
  83583. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83584. })(BABYLON || (BABYLON = {}));
  83585. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83586. var BABYLON;
  83587. (function (BABYLON) {
  83588. var OimoJSPlugin = /** @class */ (function () {
  83589. function OimoJSPlugin(iterations) {
  83590. this.name = "OimoJSPlugin";
  83591. this._tmpImpostorsArray = [];
  83592. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83593. this.BJSOIMO = OIMO;
  83594. this.world = new this.BJSOIMO.World({
  83595. iterations: iterations
  83596. });
  83597. this.world.clear();
  83598. }
  83599. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83600. this.world.gravity.copy(gravity);
  83601. };
  83602. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83603. this.world.timeStep = timeStep;
  83604. };
  83605. OimoJSPlugin.prototype.getTimeStep = function () {
  83606. return this.world.timeStep;
  83607. };
  83608. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83609. var _this = this;
  83610. impostors.forEach(function (impostor) {
  83611. impostor.beforeStep();
  83612. });
  83613. this.world.step();
  83614. impostors.forEach(function (impostor) {
  83615. impostor.afterStep();
  83616. //update the ordered impostors array
  83617. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83618. });
  83619. //check for collisions
  83620. var contact = this.world.contacts;
  83621. while (contact !== null) {
  83622. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83623. contact = contact.next;
  83624. continue;
  83625. }
  83626. //is this body colliding with any other? get the impostor
  83627. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83628. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83629. if (!mainImpostor || !collidingImpostor) {
  83630. contact = contact.next;
  83631. continue;
  83632. }
  83633. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83634. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83635. contact = contact.next;
  83636. }
  83637. };
  83638. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83639. var mass = impostor.physicsBody.mass;
  83640. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83641. };
  83642. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83643. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83644. this.applyImpulse(impostor, force, contactPoint);
  83645. };
  83646. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83647. var _this = this;
  83648. //parent-child relationship. Does this impostor has a parent impostor?
  83649. if (impostor.parent) {
  83650. if (impostor.physicsBody) {
  83651. this.removePhysicsBody(impostor);
  83652. //TODO is that needed?
  83653. impostor.forceUpdate();
  83654. }
  83655. return;
  83656. }
  83657. if (impostor.isBodyInitRequired()) {
  83658. var bodyConfig = {
  83659. name: impostor.uniqueId,
  83660. //Oimo must have mass, also for static objects.
  83661. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83662. size: [],
  83663. type: [],
  83664. pos: [],
  83665. posShape: [],
  83666. rot: [],
  83667. rotShape: [],
  83668. move: impostor.getParam("mass") !== 0,
  83669. density: impostor.getParam("mass"),
  83670. friction: impostor.getParam("friction"),
  83671. restitution: impostor.getParam("restitution"),
  83672. //Supporting older versions of Oimo
  83673. world: this.world
  83674. };
  83675. var impostors = [impostor];
  83676. var addToArray = function (parent) {
  83677. if (!parent.getChildMeshes)
  83678. return;
  83679. parent.getChildMeshes().forEach(function (m) {
  83680. if (m.physicsImpostor) {
  83681. impostors.push(m.physicsImpostor);
  83682. //m.physicsImpostor._init();
  83683. }
  83684. });
  83685. };
  83686. addToArray(impostor.object);
  83687. var checkWithEpsilon_1 = function (value) {
  83688. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83689. };
  83690. impostors.forEach(function (i) {
  83691. if (!i.object.rotationQuaternion) {
  83692. return;
  83693. }
  83694. //get the correct bounding box
  83695. var oldQuaternion = i.object.rotationQuaternion;
  83696. var rot = oldQuaternion.toEulerAngles();
  83697. var extendSize = i.getObjectExtendSize();
  83698. var radToDeg = 57.295779513082320876;
  83699. if (i === impostor) {
  83700. var center = impostor.getObjectCenter();
  83701. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83702. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83703. //Can also use Array.prototype.push.apply
  83704. bodyConfig.pos.push(center.x);
  83705. bodyConfig.pos.push(center.y);
  83706. bodyConfig.pos.push(center.z);
  83707. bodyConfig.posShape.push(0, 0, 0);
  83708. //tmp solution
  83709. bodyConfig.rot.push(rot.x * radToDeg);
  83710. bodyConfig.rot.push(rot.y * radToDeg);
  83711. bodyConfig.rot.push(rot.z * radToDeg);
  83712. bodyConfig.rotShape.push(0, 0, 0);
  83713. }
  83714. else {
  83715. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83716. bodyConfig.posShape.push(localPosition.x);
  83717. bodyConfig.posShape.push(localPosition.y);
  83718. bodyConfig.posShape.push(localPosition.z);
  83719. bodyConfig.pos.push(0, 0, 0);
  83720. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83721. bodyConfig.rot.push(0);
  83722. bodyConfig.rot.push(0);
  83723. bodyConfig.rot.push(0);
  83724. bodyConfig.rotShape.push(rot.x * radToDeg);
  83725. bodyConfig.rotShape.push(rot.y * radToDeg);
  83726. bodyConfig.rotShape.push(rot.z * radToDeg);
  83727. }
  83728. // register mesh
  83729. switch (i.type) {
  83730. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83731. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83732. case BABYLON.PhysicsImpostor.SphereImpostor:
  83733. var radiusX = extendSize.x;
  83734. var radiusY = extendSize.y;
  83735. var radiusZ = extendSize.z;
  83736. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83737. bodyConfig.type.push('sphere');
  83738. //due to the way oimo works with compounds, add 3 times
  83739. bodyConfig.size.push(size);
  83740. bodyConfig.size.push(size);
  83741. bodyConfig.size.push(size);
  83742. break;
  83743. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83744. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83745. var sizeY = checkWithEpsilon_1(extendSize.y);
  83746. bodyConfig.type.push('cylinder');
  83747. bodyConfig.size.push(sizeX);
  83748. bodyConfig.size.push(sizeY);
  83749. //due to the way oimo works with compounds, add one more value.
  83750. bodyConfig.size.push(sizeY);
  83751. break;
  83752. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83753. case BABYLON.PhysicsImpostor.BoxImpostor:
  83754. default:
  83755. var sizeX = checkWithEpsilon_1(extendSize.x);
  83756. var sizeY = checkWithEpsilon_1(extendSize.y);
  83757. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83758. bodyConfig.type.push('box');
  83759. //if (i === impostor) {
  83760. bodyConfig.size.push(sizeX);
  83761. bodyConfig.size.push(sizeY);
  83762. bodyConfig.size.push(sizeZ);
  83763. //} else {
  83764. // bodyConfig.size.push(0,0,0);
  83765. //}
  83766. break;
  83767. }
  83768. //actually not needed, but hey...
  83769. i.object.rotationQuaternion = oldQuaternion;
  83770. });
  83771. impostor.physicsBody = this.world.add(bodyConfig);
  83772. }
  83773. else {
  83774. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83775. }
  83776. impostor.setDeltaPosition(this._tmpPositionVector);
  83777. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83778. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83779. };
  83780. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83781. //impostor.physicsBody.dispose();
  83782. //Same as : (older oimo versions)
  83783. this.world.removeRigidBody(impostor.physicsBody);
  83784. };
  83785. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83786. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83787. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83788. if (!mainBody || !connectedBody) {
  83789. return;
  83790. }
  83791. var jointData = impostorJoint.joint.jointData;
  83792. var options = jointData.nativeParams || {};
  83793. var type;
  83794. var nativeJointData = {
  83795. body1: mainBody,
  83796. body2: connectedBody,
  83797. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83798. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83799. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83800. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83801. min: options.min,
  83802. max: options.max,
  83803. collision: options.collision || jointData.collision,
  83804. spring: options.spring,
  83805. //supporting older version of Oimo
  83806. world: this.world
  83807. };
  83808. switch (impostorJoint.joint.type) {
  83809. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83810. type = "jointBall";
  83811. break;
  83812. case BABYLON.PhysicsJoint.SpringJoint:
  83813. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83814. var springData = jointData;
  83815. nativeJointData.min = springData.length || nativeJointData.min;
  83816. //Max should also be set, just make sure it is at least min
  83817. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83818. case BABYLON.PhysicsJoint.DistanceJoint:
  83819. type = "jointDistance";
  83820. nativeJointData.max = jointData.maxDistance;
  83821. break;
  83822. case BABYLON.PhysicsJoint.PrismaticJoint:
  83823. type = "jointPrisme";
  83824. break;
  83825. case BABYLON.PhysicsJoint.SliderJoint:
  83826. type = "jointSlide";
  83827. break;
  83828. case BABYLON.PhysicsJoint.WheelJoint:
  83829. type = "jointWheel";
  83830. break;
  83831. case BABYLON.PhysicsJoint.HingeJoint:
  83832. default:
  83833. type = "jointHinge";
  83834. break;
  83835. }
  83836. nativeJointData.type = type;
  83837. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  83838. };
  83839. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83840. //Bug in Oimo prevents us from disposing a joint in the playground
  83841. //joint.joint.physicsJoint.dispose();
  83842. //So we will bruteforce it!
  83843. try {
  83844. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  83845. }
  83846. catch (e) {
  83847. BABYLON.Tools.Warn(e);
  83848. }
  83849. };
  83850. OimoJSPlugin.prototype.isSupported = function () {
  83851. return this.BJSOIMO !== undefined;
  83852. };
  83853. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83854. if (!impostor.physicsBody.sleeping) {
  83855. //TODO check that
  83856. /*if (impostor.physicsBody.shapes.next) {
  83857. var parentShape = this._getLastShape(impostor.physicsBody);
  83858. impostor.object.position.copyFrom(parentShape.position);
  83859. console.log(parentShape.position);
  83860. } else {*/
  83861. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  83862. //}
  83863. if (impostor.object.rotationQuaternion) {
  83864. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  83865. }
  83866. }
  83867. };
  83868. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83869. var body = impostor.physicsBody;
  83870. body.position.copy(newPosition);
  83871. body.orientation.copy(newRotation);
  83872. body.syncShapes();
  83873. body.awake();
  83874. };
  83875. /*private _getLastShape(body: any): any {
  83876. var lastShape = body.shapes;
  83877. while (lastShape.next) {
  83878. lastShape = lastShape.next;
  83879. }
  83880. return lastShape;
  83881. }*/
  83882. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83883. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  83884. };
  83885. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83886. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  83887. };
  83888. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83889. var v = impostor.physicsBody.linearVelocity;
  83890. if (!v) {
  83891. return null;
  83892. }
  83893. return new BABYLON.Vector3(v.x, v.y, v.z);
  83894. };
  83895. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83896. var v = impostor.physicsBody.angularVelocity;
  83897. if (!v) {
  83898. return null;
  83899. }
  83900. return new BABYLON.Vector3(v.x, v.y, v.z);
  83901. };
  83902. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83903. var staticBody = mass === 0;
  83904. //this will actually set the body's density and not its mass.
  83905. //But this is how oimo treats the mass variable.
  83906. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  83907. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  83908. };
  83909. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  83910. return impostor.physicsBody.shapes.density;
  83911. };
  83912. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  83913. return impostor.physicsBody.shapes.friction;
  83914. };
  83915. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83916. impostor.physicsBody.shapes.friction = friction;
  83917. };
  83918. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83919. return impostor.physicsBody.shapes.restitution;
  83920. };
  83921. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83922. impostor.physicsBody.shapes.restitution = restitution;
  83923. };
  83924. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  83925. impostor.physicsBody.sleep();
  83926. };
  83927. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  83928. impostor.physicsBody.awake();
  83929. };
  83930. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83931. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  83932. if (minDistance !== void 0) {
  83933. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  83934. }
  83935. };
  83936. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83937. //TODO separate rotational and transational motors.
  83938. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83939. if (motor) {
  83940. motor.setMotor(speed, maxForce);
  83941. }
  83942. };
  83943. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  83944. //TODO separate rotational and transational motors.
  83945. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83946. if (motor) {
  83947. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  83948. }
  83949. };
  83950. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83951. var body = impostor.physicsBody;
  83952. mesh.position.x = body.position.x;
  83953. mesh.position.y = body.position.y;
  83954. mesh.position.z = body.position.z;
  83955. if (mesh.rotationQuaternion) {
  83956. mesh.rotationQuaternion.x = body.orientation.x;
  83957. mesh.rotationQuaternion.y = body.orientation.y;
  83958. mesh.rotationQuaternion.z = body.orientation.z;
  83959. mesh.rotationQuaternion.w = body.orientation.s;
  83960. }
  83961. };
  83962. OimoJSPlugin.prototype.getRadius = function (impostor) {
  83963. return impostor.physicsBody.shapes.radius;
  83964. };
  83965. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83966. var shape = impostor.physicsBody.shapes;
  83967. result.x = shape.halfWidth * 2;
  83968. result.y = shape.halfHeight * 2;
  83969. result.z = shape.halfDepth * 2;
  83970. };
  83971. OimoJSPlugin.prototype.dispose = function () {
  83972. this.world.clear();
  83973. };
  83974. return OimoJSPlugin;
  83975. }());
  83976. BABYLON.OimoJSPlugin = OimoJSPlugin;
  83977. })(BABYLON || (BABYLON = {}));
  83978. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  83979. var BABYLON;
  83980. (function (BABYLON) {
  83981. /*
  83982. * Based on jsTGALoader - Javascript loader for TGA file
  83983. * By Vincent Thibault
  83984. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  83985. */
  83986. var TGATools = /** @class */ (function () {
  83987. function TGATools() {
  83988. }
  83989. TGATools.GetTGAHeader = function (data) {
  83990. var offset = 0;
  83991. var header = {
  83992. id_length: data[offset++],
  83993. colormap_type: data[offset++],
  83994. image_type: data[offset++],
  83995. colormap_index: data[offset++] | data[offset++] << 8,
  83996. colormap_length: data[offset++] | data[offset++] << 8,
  83997. colormap_size: data[offset++],
  83998. origin: [
  83999. data[offset++] | data[offset++] << 8,
  84000. data[offset++] | data[offset++] << 8
  84001. ],
  84002. width: data[offset++] | data[offset++] << 8,
  84003. height: data[offset++] | data[offset++] << 8,
  84004. pixel_size: data[offset++],
  84005. flags: data[offset++]
  84006. };
  84007. return header;
  84008. };
  84009. TGATools.UploadContent = function (gl, data) {
  84010. // Not enough data to contain header ?
  84011. if (data.length < 19) {
  84012. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  84013. return;
  84014. }
  84015. // Read Header
  84016. var offset = 18;
  84017. var header = TGATools.GetTGAHeader(data);
  84018. // Assume it's a valid Targa file.
  84019. if (header.id_length + offset > data.length) {
  84020. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  84021. return;
  84022. }
  84023. // Skip not needed data
  84024. offset += header.id_length;
  84025. var use_rle = false;
  84026. var use_pal = false;
  84027. var use_grey = false;
  84028. // Get some informations.
  84029. switch (header.image_type) {
  84030. case TGATools._TYPE_RLE_INDEXED:
  84031. use_rle = true;
  84032. case TGATools._TYPE_INDEXED:
  84033. use_pal = true;
  84034. break;
  84035. case TGATools._TYPE_RLE_RGB:
  84036. use_rle = true;
  84037. case TGATools._TYPE_RGB:
  84038. // use_rgb = true;
  84039. break;
  84040. case TGATools._TYPE_RLE_GREY:
  84041. use_rle = true;
  84042. case TGATools._TYPE_GREY:
  84043. use_grey = true;
  84044. break;
  84045. }
  84046. var pixel_data;
  84047. // var numAlphaBits = header.flags & 0xf;
  84048. var pixel_size = header.pixel_size >> 3;
  84049. var pixel_total = header.width * header.height * pixel_size;
  84050. // Read palettes
  84051. var palettes;
  84052. if (use_pal) {
  84053. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  84054. }
  84055. // Read LRE
  84056. if (use_rle) {
  84057. pixel_data = new Uint8Array(pixel_total);
  84058. var c, count, i;
  84059. var localOffset = 0;
  84060. var pixels = new Uint8Array(pixel_size);
  84061. while (offset < pixel_total && localOffset < pixel_total) {
  84062. c = data[offset++];
  84063. count = (c & 0x7f) + 1;
  84064. // RLE pixels
  84065. if (c & 0x80) {
  84066. // Bind pixel tmp array
  84067. for (i = 0; i < pixel_size; ++i) {
  84068. pixels[i] = data[offset++];
  84069. }
  84070. // Copy pixel array
  84071. for (i = 0; i < count; ++i) {
  84072. pixel_data.set(pixels, localOffset + i * pixel_size);
  84073. }
  84074. localOffset += pixel_size * count;
  84075. }
  84076. // Raw pixels
  84077. else {
  84078. count *= pixel_size;
  84079. for (i = 0; i < count; ++i) {
  84080. pixel_data[localOffset + i] = data[offset++];
  84081. }
  84082. localOffset += count;
  84083. }
  84084. }
  84085. }
  84086. // RAW Pixels
  84087. else {
  84088. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84089. }
  84090. // Load to texture
  84091. var x_start, y_start, x_step, y_step, y_end, x_end;
  84092. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84093. default:
  84094. case TGATools._ORIGIN_UL:
  84095. x_start = 0;
  84096. x_step = 1;
  84097. x_end = header.width;
  84098. y_start = 0;
  84099. y_step = 1;
  84100. y_end = header.height;
  84101. break;
  84102. case TGATools._ORIGIN_BL:
  84103. x_start = 0;
  84104. x_step = 1;
  84105. x_end = header.width;
  84106. y_start = header.height - 1;
  84107. y_step = -1;
  84108. y_end = -1;
  84109. break;
  84110. case TGATools._ORIGIN_UR:
  84111. x_start = header.width - 1;
  84112. x_step = -1;
  84113. x_end = -1;
  84114. y_start = 0;
  84115. y_step = 1;
  84116. y_end = header.height;
  84117. break;
  84118. case TGATools._ORIGIN_BR:
  84119. x_start = header.width - 1;
  84120. x_step = -1;
  84121. x_end = -1;
  84122. y_start = header.height - 1;
  84123. y_step = -1;
  84124. y_end = -1;
  84125. break;
  84126. }
  84127. // Load the specify method
  84128. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84129. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84130. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84131. };
  84132. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84133. var image = pixel_data, colormap = palettes;
  84134. var width = header.width, height = header.height;
  84135. var color, i = 0, x, y;
  84136. var imageData = new Uint8Array(width * height * 4);
  84137. for (y = y_start; y !== y_end; y += y_step) {
  84138. for (x = x_start; x !== x_end; x += x_step, i++) {
  84139. color = image[i];
  84140. imageData[(x + width * y) * 4 + 3] = 255;
  84141. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84142. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84143. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84144. }
  84145. }
  84146. return imageData;
  84147. };
  84148. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84149. var image = pixel_data;
  84150. var width = header.width, height = header.height;
  84151. var color, i = 0, x, y;
  84152. var imageData = new Uint8Array(width * height * 4);
  84153. for (y = y_start; y !== y_end; y += y_step) {
  84154. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84155. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84156. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84157. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84158. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84159. imageData[(x + width * y) * 4 + 0] = r;
  84160. imageData[(x + width * y) * 4 + 1] = g;
  84161. imageData[(x + width * y) * 4 + 2] = b;
  84162. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84163. }
  84164. }
  84165. return imageData;
  84166. };
  84167. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84168. var image = pixel_data;
  84169. var width = header.width, height = header.height;
  84170. var i = 0, x, y;
  84171. var imageData = new Uint8Array(width * height * 4);
  84172. for (y = y_start; y !== y_end; y += y_step) {
  84173. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84174. imageData[(x + width * y) * 4 + 3] = 255;
  84175. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84176. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84177. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84178. }
  84179. }
  84180. return imageData;
  84181. };
  84182. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84183. var image = pixel_data;
  84184. var width = header.width, height = header.height;
  84185. var i = 0, x, y;
  84186. var imageData = new Uint8Array(width * height * 4);
  84187. for (y = y_start; y !== y_end; y += y_step) {
  84188. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84189. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84190. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84191. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84192. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84193. }
  84194. }
  84195. return imageData;
  84196. };
  84197. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84198. var image = pixel_data;
  84199. var width = header.width, height = header.height;
  84200. var color, i = 0, x, y;
  84201. var imageData = new Uint8Array(width * height * 4);
  84202. for (y = y_start; y !== y_end; y += y_step) {
  84203. for (x = x_start; x !== x_end; x += x_step, i++) {
  84204. color = image[i];
  84205. imageData[(x + width * y) * 4 + 0] = color;
  84206. imageData[(x + width * y) * 4 + 1] = color;
  84207. imageData[(x + width * y) * 4 + 2] = color;
  84208. imageData[(x + width * y) * 4 + 3] = 255;
  84209. }
  84210. }
  84211. return imageData;
  84212. };
  84213. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84214. var image = pixel_data;
  84215. var width = header.width, height = header.height;
  84216. var i = 0, x, y;
  84217. var imageData = new Uint8Array(width * height * 4);
  84218. for (y = y_start; y !== y_end; y += y_step) {
  84219. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84220. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84221. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84222. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84223. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84224. }
  84225. }
  84226. return imageData;
  84227. };
  84228. //private static _TYPE_NO_DATA = 0;
  84229. TGATools._TYPE_INDEXED = 1;
  84230. TGATools._TYPE_RGB = 2;
  84231. TGATools._TYPE_GREY = 3;
  84232. TGATools._TYPE_RLE_INDEXED = 9;
  84233. TGATools._TYPE_RLE_RGB = 10;
  84234. TGATools._TYPE_RLE_GREY = 11;
  84235. TGATools._ORIGIN_MASK = 0x30;
  84236. TGATools._ORIGIN_SHIFT = 0x04;
  84237. TGATools._ORIGIN_BL = 0x00;
  84238. TGATools._ORIGIN_BR = 0x01;
  84239. TGATools._ORIGIN_UL = 0x02;
  84240. TGATools._ORIGIN_UR = 0x03;
  84241. return TGATools;
  84242. }());
  84243. BABYLON.TGATools = TGATools;
  84244. })(BABYLON || (BABYLON = {}));
  84245. //# sourceMappingURL=babylon.tga.js.map
  84246. var BABYLON;
  84247. (function (BABYLON) {
  84248. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84249. // All values and structures referenced from:
  84250. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84251. var DDS_MAGIC = 0x20534444;
  84252. var
  84253. //DDSD_CAPS = 0x1,
  84254. //DDSD_HEIGHT = 0x2,
  84255. //DDSD_WIDTH = 0x4,
  84256. //DDSD_PITCH = 0x8,
  84257. //DDSD_PIXELFORMAT = 0x1000,
  84258. DDSD_MIPMAPCOUNT = 0x20000;
  84259. //DDSD_LINEARSIZE = 0x80000,
  84260. //DDSD_DEPTH = 0x800000;
  84261. // var DDSCAPS_COMPLEX = 0x8,
  84262. // DDSCAPS_MIPMAP = 0x400000,
  84263. // DDSCAPS_TEXTURE = 0x1000;
  84264. var DDSCAPS2_CUBEMAP = 0x200;
  84265. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84266. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84267. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84268. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84269. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84270. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84271. // DDSCAPS2_VOLUME = 0x200000;
  84272. var
  84273. //DDPF_ALPHAPIXELS = 0x1,
  84274. //DDPF_ALPHA = 0x2,
  84275. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84276. //DDPF_YUV = 0x200,
  84277. DDPF_LUMINANCE = 0x20000;
  84278. function FourCCToInt32(value) {
  84279. return value.charCodeAt(0) +
  84280. (value.charCodeAt(1) << 8) +
  84281. (value.charCodeAt(2) << 16) +
  84282. (value.charCodeAt(3) << 24);
  84283. }
  84284. function Int32ToFourCC(value) {
  84285. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84286. }
  84287. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84288. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84289. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84290. var FOURCC_DX10 = FourCCToInt32("DX10");
  84291. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84292. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84293. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84294. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84295. var headerLengthInt = 31; // The header length in 32 bit ints
  84296. // Offsets into the header array
  84297. var off_magic = 0;
  84298. var off_size = 1;
  84299. var off_flags = 2;
  84300. var off_height = 3;
  84301. var off_width = 4;
  84302. var off_mipmapCount = 7;
  84303. var off_pfFlags = 20;
  84304. var off_pfFourCC = 21;
  84305. var off_RGBbpp = 22;
  84306. var off_RMask = 23;
  84307. var off_GMask = 24;
  84308. var off_BMask = 25;
  84309. var off_AMask = 26;
  84310. // var off_caps1 = 27;
  84311. var off_caps2 = 28;
  84312. // var off_caps3 = 29;
  84313. // var off_caps4 = 30;
  84314. var off_dxgiFormat = 32;
  84315. ;
  84316. var DDSTools = /** @class */ (function () {
  84317. function DDSTools() {
  84318. }
  84319. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84320. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84321. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84322. var mipmapCount = 1;
  84323. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84324. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84325. }
  84326. var fourCC = header[off_pfFourCC];
  84327. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84328. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84329. switch (fourCC) {
  84330. case FOURCC_D3DFMT_R16G16B16A16F:
  84331. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84332. break;
  84333. case FOURCC_D3DFMT_R32G32B32A32F:
  84334. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84335. break;
  84336. case FOURCC_DX10:
  84337. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84338. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84339. break;
  84340. }
  84341. }
  84342. return {
  84343. width: header[off_width],
  84344. height: header[off_height],
  84345. mipmapCount: mipmapCount,
  84346. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84347. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84348. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84349. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84350. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84351. dxgiFormat: dxgiFormat,
  84352. textureType: textureType
  84353. };
  84354. };
  84355. DDSTools._ToHalfFloat = function (value) {
  84356. if (!DDSTools._FloatView) {
  84357. DDSTools._FloatView = new Float32Array(1);
  84358. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84359. }
  84360. DDSTools._FloatView[0] = value;
  84361. var x = DDSTools._Int32View[0];
  84362. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84363. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84364. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84365. /* If zero, or denormal, or exponent underflows too much for a denormal
  84366. * half, return signed zero. */
  84367. if (e < 103) {
  84368. return bits;
  84369. }
  84370. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84371. if (e > 142) {
  84372. bits |= 0x7c00;
  84373. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84374. * not Inf, so make sure we set one mantissa bit too. */
  84375. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84376. return bits;
  84377. }
  84378. /* If exponent underflows but not too much, return a denormal */
  84379. if (e < 113) {
  84380. m |= 0x0800;
  84381. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84382. * to 1, which is OK. */
  84383. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84384. return bits;
  84385. }
  84386. bits |= ((e - 112) << 10) | (m >> 1);
  84387. bits += m & 1;
  84388. return bits;
  84389. };
  84390. DDSTools._FromHalfFloat = function (value) {
  84391. var s = (value & 0x8000) >> 15;
  84392. var e = (value & 0x7C00) >> 10;
  84393. var f = value & 0x03FF;
  84394. if (e === 0) {
  84395. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84396. }
  84397. else if (e == 0x1F) {
  84398. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84399. }
  84400. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84401. };
  84402. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84403. var destArray = new Float32Array(dataLength);
  84404. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84405. var index = 0;
  84406. for (var y = 0; y < height; y++) {
  84407. for (var x = 0; x < width; x++) {
  84408. var srcPos = (x + y * width) * 4;
  84409. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84410. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84411. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84412. if (DDSTools.StoreLODInAlphaChannel) {
  84413. destArray[index + 3] = lod;
  84414. }
  84415. else {
  84416. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84417. }
  84418. index += 4;
  84419. }
  84420. }
  84421. return destArray;
  84422. };
  84423. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84424. if (DDSTools.StoreLODInAlphaChannel) {
  84425. var destArray = new Uint16Array(dataLength);
  84426. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84427. var index = 0;
  84428. for (var y = 0; y < height; y++) {
  84429. for (var x = 0; x < width; x++) {
  84430. var srcPos = (x + y * width) * 4;
  84431. destArray[index] = srcData[srcPos];
  84432. destArray[index + 1] = srcData[srcPos + 1];
  84433. destArray[index + 2] = srcData[srcPos + 2];
  84434. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84435. index += 4;
  84436. }
  84437. }
  84438. return destArray;
  84439. }
  84440. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84441. };
  84442. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84443. if (DDSTools.StoreLODInAlphaChannel) {
  84444. var destArray = new Float32Array(dataLength);
  84445. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84446. var index = 0;
  84447. for (var y = 0; y < height; y++) {
  84448. for (var x = 0; x < width; x++) {
  84449. var srcPos = (x + y * width) * 4;
  84450. destArray[index] = srcData[srcPos];
  84451. destArray[index + 1] = srcData[srcPos + 1];
  84452. destArray[index + 2] = srcData[srcPos + 2];
  84453. destArray[index + 3] = lod;
  84454. index += 4;
  84455. }
  84456. }
  84457. return destArray;
  84458. }
  84459. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84460. };
  84461. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84462. var destArray = new Uint8Array(dataLength);
  84463. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84464. var index = 0;
  84465. for (var y = 0; y < height; y++) {
  84466. for (var x = 0; x < width; x++) {
  84467. var srcPos = (x + y * width) * 4;
  84468. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84469. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84470. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84471. if (DDSTools.StoreLODInAlphaChannel) {
  84472. destArray[index + 3] = lod;
  84473. }
  84474. else {
  84475. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84476. }
  84477. index += 4;
  84478. }
  84479. }
  84480. return destArray;
  84481. };
  84482. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84483. var destArray = new Uint8Array(dataLength);
  84484. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84485. var index = 0;
  84486. for (var y = 0; y < height; y++) {
  84487. for (var x = 0; x < width; x++) {
  84488. var srcPos = (x + y * width) * 4;
  84489. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  84490. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  84491. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  84492. if (DDSTools.StoreLODInAlphaChannel) {
  84493. destArray[index + 3] = lod;
  84494. }
  84495. else {
  84496. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  84497. }
  84498. index += 4;
  84499. }
  84500. }
  84501. return destArray;
  84502. };
  84503. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  84504. var byteArray = new Uint8Array(dataLength);
  84505. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84506. var index = 0;
  84507. for (var y = 0; y < height; y++) {
  84508. for (var x = 0; x < width; x++) {
  84509. var srcPos = (x + y * width) * 4;
  84510. byteArray[index] = srcData[srcPos + rOffset];
  84511. byteArray[index + 1] = srcData[srcPos + gOffset];
  84512. byteArray[index + 2] = srcData[srcPos + bOffset];
  84513. byteArray[index + 3] = srcData[srcPos + aOffset];
  84514. index += 4;
  84515. }
  84516. }
  84517. return byteArray;
  84518. };
  84519. DDSTools._ExtractLongWordOrder = function (value) {
  84520. if (value === 0 || value === 255 || value === -16777216) {
  84521. return 0;
  84522. }
  84523. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84524. };
  84525. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84526. var byteArray = new Uint8Array(dataLength);
  84527. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84528. var index = 0;
  84529. for (var y = 0; y < height; y++) {
  84530. for (var x = 0; x < width; x++) {
  84531. var srcPos = (x + y * width) * 3;
  84532. byteArray[index] = srcData[srcPos + rOffset];
  84533. byteArray[index + 1] = srcData[srcPos + gOffset];
  84534. byteArray[index + 2] = srcData[srcPos + bOffset];
  84535. index += 3;
  84536. }
  84537. }
  84538. return byteArray;
  84539. };
  84540. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84541. var byteArray = new Uint8Array(dataLength);
  84542. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84543. var index = 0;
  84544. for (var y = 0; y < height; y++) {
  84545. for (var x = 0; x < width; x++) {
  84546. var srcPos = (x + y * width);
  84547. byteArray[index] = srcData[srcPos];
  84548. index++;
  84549. }
  84550. }
  84551. return byteArray;
  84552. };
  84553. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84554. if (lodIndex === void 0) { lodIndex = -1; }
  84555. var sphericalPolynomialFaces = null;
  84556. if (info.sphericalPolynomial) {
  84557. sphericalPolynomialFaces = new Array();
  84558. }
  84559. var ext = engine.getCaps().s3tc;
  84560. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84561. var fourCC, width, height, dataLength = 0, dataOffset;
  84562. var byteArray, mipmapCount, mip;
  84563. var internalFormat = 0;
  84564. var format = 0;
  84565. var blockBytes = 1;
  84566. if (header[off_magic] !== DDS_MAGIC) {
  84567. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84568. return;
  84569. }
  84570. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84571. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84572. return;
  84573. }
  84574. if (info.isCompressed && !ext) {
  84575. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84576. return;
  84577. }
  84578. var bpp = header[off_RGBbpp];
  84579. dataOffset = header[off_size] + 4;
  84580. var computeFormats = false;
  84581. if (info.isFourCC) {
  84582. fourCC = header[off_pfFourCC];
  84583. switch (fourCC) {
  84584. case FOURCC_DXT1:
  84585. blockBytes = 8;
  84586. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84587. break;
  84588. case FOURCC_DXT3:
  84589. blockBytes = 16;
  84590. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84591. break;
  84592. case FOURCC_DXT5:
  84593. blockBytes = 16;
  84594. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84595. break;
  84596. case FOURCC_D3DFMT_R16G16B16A16F:
  84597. computeFormats = true;
  84598. break;
  84599. case FOURCC_D3DFMT_R32G32B32A32F:
  84600. computeFormats = true;
  84601. break;
  84602. case FOURCC_DX10:
  84603. // There is an additionnal header so dataOffset need to be changed
  84604. dataOffset += 5 * 4; // 5 uints
  84605. var supported = false;
  84606. switch (info.dxgiFormat) {
  84607. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84608. computeFormats = true;
  84609. supported = true;
  84610. break;
  84611. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84612. info.isRGB = true;
  84613. info.isFourCC = false;
  84614. bpp = 32;
  84615. supported = true;
  84616. break;
  84617. }
  84618. if (supported) {
  84619. break;
  84620. }
  84621. default:
  84622. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84623. return;
  84624. }
  84625. }
  84626. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84627. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84628. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84629. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84630. if (computeFormats) {
  84631. format = engine._getWebGLTextureType(info.textureType);
  84632. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84633. }
  84634. mipmapCount = 1;
  84635. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84636. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84637. }
  84638. for (var face = 0; face < faces; face++) {
  84639. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84640. width = header[off_width];
  84641. height = header[off_height];
  84642. for (mip = 0; mip < mipmapCount; ++mip) {
  84643. if (lodIndex === -1 || lodIndex === mip) {
  84644. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84645. var i = (lodIndex === -1) ? mip : 0;
  84646. if (!info.isCompressed && info.isFourCC) {
  84647. dataLength = width * height * 4;
  84648. var floatArray = null;
  84649. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84650. if (bpp === 128) {
  84651. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84652. if (sphericalPolynomialFaces && i == 0) {
  84653. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84654. }
  84655. }
  84656. else if (bpp === 64) {
  84657. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84658. if (sphericalPolynomialFaces && i == 0) {
  84659. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84660. }
  84661. }
  84662. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84663. format = engine._getWebGLTextureType(info.textureType);
  84664. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84665. }
  84666. else {
  84667. if (bpp === 128) {
  84668. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84669. if (sphericalPolynomialFaces && i == 0) {
  84670. sphericalPolynomialFaces.push(floatArray);
  84671. }
  84672. }
  84673. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84674. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84675. if (sphericalPolynomialFaces && i == 0) {
  84676. sphericalPolynomialFaces.push(floatArray);
  84677. }
  84678. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84679. format = engine._getWebGLTextureType(info.textureType);
  84680. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84681. }
  84682. else { // 64
  84683. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84684. if (sphericalPolynomialFaces && i == 0) {
  84685. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84686. }
  84687. }
  84688. }
  84689. if (floatArray) {
  84690. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84691. }
  84692. }
  84693. else if (info.isRGB) {
  84694. if (bpp === 24) {
  84695. dataLength = width * height * 3;
  84696. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84697. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84698. }
  84699. else { // 32
  84700. dataLength = width * height * 4;
  84701. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84702. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84703. }
  84704. }
  84705. else if (info.isLuminance) {
  84706. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84707. var unpaddedRowSize = width;
  84708. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84709. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84710. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84711. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84712. }
  84713. else {
  84714. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84715. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84716. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84717. }
  84718. }
  84719. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84720. width *= 0.5;
  84721. height *= 0.5;
  84722. width = Math.max(1.0, width);
  84723. height = Math.max(1.0, height);
  84724. }
  84725. if (currentFace !== undefined) {
  84726. // Loading a single face
  84727. break;
  84728. }
  84729. }
  84730. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  84731. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  84732. size: header[off_width],
  84733. right: sphericalPolynomialFaces[0],
  84734. left: sphericalPolynomialFaces[1],
  84735. up: sphericalPolynomialFaces[2],
  84736. down: sphericalPolynomialFaces[3],
  84737. front: sphericalPolynomialFaces[4],
  84738. back: sphericalPolynomialFaces[5],
  84739. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  84740. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84741. gammaSpace: false,
  84742. });
  84743. }
  84744. else {
  84745. info.sphericalPolynomial = undefined;
  84746. }
  84747. };
  84748. DDSTools.StoreLODInAlphaChannel = false;
  84749. return DDSTools;
  84750. }());
  84751. BABYLON.DDSTools = DDSTools;
  84752. })(BABYLON || (BABYLON = {}));
  84753. //# sourceMappingURL=babylon.dds.js.map
  84754. var BABYLON;
  84755. (function (BABYLON) {
  84756. /**
  84757. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84758. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84759. */
  84760. var KhronosTextureContainer = /** @class */ (function () {
  84761. /**
  84762. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84763. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84764. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84765. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84766. */
  84767. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84768. this.arrayBuffer = arrayBuffer;
  84769. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84770. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84771. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84772. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84773. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84774. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84775. BABYLON.Tools.Error("texture missing KTX identifier");
  84776. return;
  84777. }
  84778. // load the reset of the header in native 32 bit int
  84779. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84780. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84781. var oppositeEndianess = header[0] === 0x01020304;
  84782. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84783. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84784. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84785. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84786. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84787. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84788. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84789. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84790. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84791. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84792. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84793. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84794. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84795. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84796. if (this.glType !== 0) {
  84797. BABYLON.Tools.Error("only compressed formats currently supported");
  84798. return;
  84799. }
  84800. else {
  84801. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84802. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84803. }
  84804. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84805. BABYLON.Tools.Error("only 2D textures currently supported");
  84806. return;
  84807. }
  84808. if (this.numberOfArrayElements !== 0) {
  84809. BABYLON.Tools.Error("texture arrays not currently supported");
  84810. return;
  84811. }
  84812. if (this.numberOfFaces !== facesExpected) {
  84813. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84814. return;
  84815. }
  84816. // we now have a completely validated file, so could use existence of loadType as success
  84817. // would need to make this more elaborate & adjust checks above to support more than one load type
  84818. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84819. }
  84820. // not as fast hardware based, but will probably never need to use
  84821. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84822. return ((val & 0xFF) << 24)
  84823. | ((val & 0xFF00) << 8)
  84824. | ((val >> 8) & 0xFF00)
  84825. | ((val >> 24) & 0xFF);
  84826. };
  84827. /**
  84828. * It is assumed that the texture has already been created & is currently bound
  84829. */
  84830. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  84831. switch (this.loadType) {
  84832. case KhronosTextureContainer.COMPRESSED_2D:
  84833. this._upload2DCompressedLevels(gl, loadMipmaps);
  84834. break;
  84835. case KhronosTextureContainer.TEX_2D:
  84836. case KhronosTextureContainer.COMPRESSED_3D:
  84837. case KhronosTextureContainer.TEX_3D:
  84838. }
  84839. };
  84840. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  84841. // initialize width & height for level 1
  84842. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  84843. var width = this.pixelWidth;
  84844. var height = this.pixelHeight;
  84845. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  84846. for (var level = 0; level < mipmapCount; level++) {
  84847. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  84848. for (var face = 0; face < this.numberOfFaces; face++) {
  84849. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  84850. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  84851. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  84852. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  84853. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  84854. }
  84855. width = Math.max(1.0, width * 0.5);
  84856. height = Math.max(1.0, height * 0.5);
  84857. }
  84858. };
  84859. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  84860. // load types
  84861. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  84862. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  84863. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  84864. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  84865. return KhronosTextureContainer;
  84866. }());
  84867. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  84868. })(BABYLON || (BABYLON = {}));
  84869. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  84870. var BABYLON;
  84871. (function (BABYLON) {
  84872. var Debug;
  84873. (function (Debug) {
  84874. /**
  84875. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  84876. */
  84877. var SkeletonViewer = /** @class */ (function () {
  84878. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  84879. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  84880. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  84881. this.skeleton = skeleton;
  84882. this.mesh = mesh;
  84883. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  84884. this.renderingGroupId = renderingGroupId;
  84885. this.color = BABYLON.Color3.White();
  84886. this._debugLines = new Array();
  84887. this._isEnabled = false;
  84888. this._scene = scene;
  84889. this.update();
  84890. this._renderFunction = this.update.bind(this);
  84891. }
  84892. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  84893. get: function () {
  84894. return this._isEnabled;
  84895. },
  84896. set: function (value) {
  84897. if (this._isEnabled === value) {
  84898. return;
  84899. }
  84900. this._isEnabled = value;
  84901. if (value) {
  84902. this._scene.registerBeforeRender(this._renderFunction);
  84903. }
  84904. else {
  84905. this._scene.unregisterBeforeRender(this._renderFunction);
  84906. }
  84907. },
  84908. enumerable: true,
  84909. configurable: true
  84910. });
  84911. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  84912. if (x === void 0) { x = 0; }
  84913. if (y === void 0) { y = 0; }
  84914. if (z === void 0) { z = 0; }
  84915. var tmat = BABYLON.Tmp.Matrix[0];
  84916. var parentBone = bone.getParent();
  84917. tmat.copyFrom(bone.getLocalMatrix());
  84918. if (x !== 0 || y !== 0 || z !== 0) {
  84919. var tmat2 = BABYLON.Tmp.Matrix[1];
  84920. BABYLON.Matrix.IdentityToRef(tmat2);
  84921. tmat2.m[12] = x;
  84922. tmat2.m[13] = y;
  84923. tmat2.m[14] = z;
  84924. tmat2.multiplyToRef(tmat, tmat);
  84925. }
  84926. if (parentBone) {
  84927. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  84928. }
  84929. tmat.multiplyToRef(meshMat, tmat);
  84930. position.x = tmat.m[12];
  84931. position.y = tmat.m[13];
  84932. position.z = tmat.m[14];
  84933. };
  84934. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  84935. var len = bones.length;
  84936. var meshPos = this.mesh.position;
  84937. for (var i = 0; i < len; i++) {
  84938. var bone = bones[i];
  84939. var points = this._debugLines[i];
  84940. if (!points) {
  84941. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84942. this._debugLines[i] = points;
  84943. }
  84944. this._getBonePosition(points[0], bone, meshMat);
  84945. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  84946. points[0].subtractInPlace(meshPos);
  84947. points[1].subtractInPlace(meshPos);
  84948. }
  84949. };
  84950. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  84951. var len = bones.length;
  84952. var boneNum = 0;
  84953. var meshPos = this.mesh.position;
  84954. for (var i = len - 1; i >= 0; i--) {
  84955. var childBone = bones[i];
  84956. var parentBone = childBone.getParent();
  84957. if (!parentBone) {
  84958. continue;
  84959. }
  84960. var points = this._debugLines[boneNum];
  84961. if (!points) {
  84962. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84963. this._debugLines[boneNum] = points;
  84964. }
  84965. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  84966. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  84967. points[0].subtractInPlace(meshPos);
  84968. points[1].subtractInPlace(meshPos);
  84969. boneNum++;
  84970. }
  84971. };
  84972. SkeletonViewer.prototype.update = function () {
  84973. if (this.autoUpdateBonesMatrices) {
  84974. this.skeleton.computeAbsoluteTransforms();
  84975. }
  84976. if (this.skeleton.bones[0].length === undefined) {
  84977. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84978. }
  84979. else {
  84980. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84981. }
  84982. if (!this._debugMesh) {
  84983. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  84984. this._debugMesh.renderingGroupId = this.renderingGroupId;
  84985. }
  84986. else {
  84987. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  84988. }
  84989. this._debugMesh.position.copyFrom(this.mesh.position);
  84990. this._debugMesh.color = this.color;
  84991. };
  84992. SkeletonViewer.prototype.dispose = function () {
  84993. if (this._debugMesh) {
  84994. this.isEnabled = false;
  84995. this._debugMesh.dispose();
  84996. this._debugMesh = null;
  84997. }
  84998. };
  84999. return SkeletonViewer;
  85000. }());
  85001. Debug.SkeletonViewer = SkeletonViewer;
  85002. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85003. })(BABYLON || (BABYLON = {}));
  85004. //# sourceMappingURL=babylon.skeletonViewer.js.map
  85005. /**
  85006. * Module Debug contains the (visual) components to debug a scene correctly
  85007. */
  85008. var BABYLON;
  85009. (function (BABYLON) {
  85010. var Debug;
  85011. (function (Debug) {
  85012. /**
  85013. * The Axes viewer will show 3 axes in a specific point in space
  85014. */
  85015. var AxesViewer = /** @class */ (function () {
  85016. function AxesViewer(scene, scaleLines) {
  85017. if (scaleLines === void 0) { scaleLines = 1; }
  85018. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85019. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85020. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85021. this.scaleLines = 1;
  85022. this.scaleLines = scaleLines;
  85023. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  85024. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  85025. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  85026. this._xmesh.renderingGroupId = 2;
  85027. this._ymesh.renderingGroupId = 2;
  85028. this._zmesh.renderingGroupId = 2;
  85029. this._xmesh.material.checkReadyOnlyOnce = true;
  85030. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  85031. this._ymesh.material.checkReadyOnlyOnce = true;
  85032. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  85033. this._zmesh.material.checkReadyOnlyOnce = true;
  85034. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  85035. this.scene = scene;
  85036. }
  85037. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  85038. var scaleLines = this.scaleLines;
  85039. if (this._xmesh) {
  85040. this._xmesh.position.copyFrom(position);
  85041. }
  85042. if (this._ymesh) {
  85043. this._ymesh.position.copyFrom(position);
  85044. }
  85045. if (this._zmesh) {
  85046. this._zmesh.position.copyFrom(position);
  85047. }
  85048. var point2 = this._xline[1];
  85049. point2.x = xaxis.x * scaleLines;
  85050. point2.y = xaxis.y * scaleLines;
  85051. point2.z = xaxis.z * scaleLines;
  85052. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  85053. point2 = this._yline[1];
  85054. point2.x = yaxis.x * scaleLines;
  85055. point2.y = yaxis.y * scaleLines;
  85056. point2.z = yaxis.z * scaleLines;
  85057. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  85058. point2 = this._zline[1];
  85059. point2.x = zaxis.x * scaleLines;
  85060. point2.y = zaxis.y * scaleLines;
  85061. point2.z = zaxis.z * scaleLines;
  85062. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  85063. };
  85064. AxesViewer.prototype.dispose = function () {
  85065. if (this._xmesh) {
  85066. this._xmesh.dispose();
  85067. }
  85068. if (this._ymesh) {
  85069. this._ymesh.dispose();
  85070. }
  85071. if (this._zmesh) {
  85072. this._zmesh.dispose();
  85073. }
  85074. this._xmesh = null;
  85075. this._ymesh = null;
  85076. this._zmesh = null;
  85077. this.scene = null;
  85078. };
  85079. return AxesViewer;
  85080. }());
  85081. Debug.AxesViewer = AxesViewer;
  85082. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85083. })(BABYLON || (BABYLON = {}));
  85084. //# sourceMappingURL=babylon.axesViewer.js.map
  85085. var BABYLON;
  85086. (function (BABYLON) {
  85087. var Debug;
  85088. (function (Debug) {
  85089. /**
  85090. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85091. */
  85092. var BoneAxesViewer = /** @class */ (function (_super) {
  85093. __extends(BoneAxesViewer, _super);
  85094. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85095. if (scaleLines === void 0) { scaleLines = 1; }
  85096. var _this = _super.call(this, scene, scaleLines) || this;
  85097. _this.pos = BABYLON.Vector3.Zero();
  85098. _this.xaxis = BABYLON.Vector3.Zero();
  85099. _this.yaxis = BABYLON.Vector3.Zero();
  85100. _this.zaxis = BABYLON.Vector3.Zero();
  85101. _this.mesh = mesh;
  85102. _this.bone = bone;
  85103. return _this;
  85104. }
  85105. BoneAxesViewer.prototype.update = function () {
  85106. if (!this.mesh || !this.bone) {
  85107. return;
  85108. }
  85109. var bone = this.bone;
  85110. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85111. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85112. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85113. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85114. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85115. };
  85116. BoneAxesViewer.prototype.dispose = function () {
  85117. if (this.mesh) {
  85118. this.mesh = null;
  85119. this.bone = null;
  85120. _super.prototype.dispose.call(this);
  85121. }
  85122. };
  85123. return BoneAxesViewer;
  85124. }(Debug.AxesViewer));
  85125. Debug.BoneAxesViewer = BoneAxesViewer;
  85126. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85127. })(BABYLON || (BABYLON = {}));
  85128. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85129. var BABYLON;
  85130. (function (BABYLON) {
  85131. var RayHelper = /** @class */ (function () {
  85132. function RayHelper(ray) {
  85133. this.ray = ray;
  85134. }
  85135. RayHelper.CreateAndShow = function (ray, scene, color) {
  85136. var helper = new RayHelper(ray);
  85137. helper.show(scene, color);
  85138. return helper;
  85139. };
  85140. RayHelper.prototype.show = function (scene, color) {
  85141. if (!this._renderFunction && this.ray) {
  85142. var ray = this.ray;
  85143. this._renderFunction = this._render.bind(this);
  85144. this._scene = scene;
  85145. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85146. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85147. if (this._renderFunction) {
  85148. this._scene.registerBeforeRender(this._renderFunction);
  85149. }
  85150. }
  85151. if (color && this._renderLine) {
  85152. this._renderLine.color.copyFrom(color);
  85153. }
  85154. };
  85155. RayHelper.prototype.hide = function () {
  85156. if (this._renderFunction && this._scene) {
  85157. this._scene.unregisterBeforeRender(this._renderFunction);
  85158. this._scene = null;
  85159. this._renderFunction = null;
  85160. if (this._renderLine) {
  85161. this._renderLine.dispose();
  85162. this._renderLine = null;
  85163. }
  85164. this._renderPoints = [];
  85165. }
  85166. };
  85167. RayHelper.prototype._render = function () {
  85168. var ray = this.ray;
  85169. if (!ray) {
  85170. return;
  85171. }
  85172. var point = this._renderPoints[1];
  85173. var len = Math.min(ray.length, 1000000);
  85174. point.copyFrom(ray.direction);
  85175. point.scaleInPlace(len);
  85176. point.addInPlace(ray.origin);
  85177. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85178. };
  85179. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85180. this._attachedToMesh = mesh;
  85181. var ray = this.ray;
  85182. if (!ray) {
  85183. return;
  85184. }
  85185. if (!ray.direction) {
  85186. ray.direction = BABYLON.Vector3.Zero();
  85187. }
  85188. if (!ray.origin) {
  85189. ray.origin = BABYLON.Vector3.Zero();
  85190. }
  85191. if (length) {
  85192. ray.length = length;
  85193. }
  85194. if (!meshSpaceOrigin) {
  85195. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85196. }
  85197. if (!meshSpaceDirection) {
  85198. // -1 so that this will work with Mesh.lookAt
  85199. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85200. }
  85201. if (!this._meshSpaceDirection) {
  85202. this._meshSpaceDirection = meshSpaceDirection.clone();
  85203. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85204. }
  85205. else {
  85206. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85207. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85208. }
  85209. if (!this._updateToMeshFunction) {
  85210. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85211. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85212. }
  85213. this._updateToMesh();
  85214. };
  85215. RayHelper.prototype.detachFromMesh = function () {
  85216. if (this._attachedToMesh) {
  85217. if (this._updateToMeshFunction) {
  85218. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85219. }
  85220. this._attachedToMesh = null;
  85221. this._updateToMeshFunction = null;
  85222. }
  85223. };
  85224. RayHelper.prototype._updateToMesh = function () {
  85225. var ray = this.ray;
  85226. if (!this._attachedToMesh || !ray) {
  85227. return;
  85228. }
  85229. if (this._attachedToMesh._isDisposed) {
  85230. this.detachFromMesh();
  85231. return;
  85232. }
  85233. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85234. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85235. };
  85236. RayHelper.prototype.dispose = function () {
  85237. this.hide();
  85238. this.detachFromMesh();
  85239. this.ray = null;
  85240. };
  85241. return RayHelper;
  85242. }());
  85243. BABYLON.RayHelper = RayHelper;
  85244. })(BABYLON || (BABYLON = {}));
  85245. //# sourceMappingURL=babylon.rayHelper.js.map
  85246. var BABYLON;
  85247. (function (BABYLON) {
  85248. // load the inspector using require, if not present in the global namespace.
  85249. var DebugLayer = /** @class */ (function () {
  85250. function DebugLayer(scene) {
  85251. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85252. this._scene = scene;
  85253. // load inspector using require, if it doesn't exist on the global namespace.
  85254. }
  85255. /** Creates the inspector window. */
  85256. DebugLayer.prototype._createInspector = function (config) {
  85257. if (config === void 0) { config = {}; }
  85258. var popup = config.popup || false;
  85259. var initialTab = config.initialTab || 0;
  85260. var parentElement = config.parentElement || null;
  85261. if (!this._inspector) {
  85262. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85263. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85264. } // else nothing to do,; instance is already existing
  85265. };
  85266. DebugLayer.prototype.isVisible = function () {
  85267. if (!this._inspector) {
  85268. return false;
  85269. }
  85270. return true;
  85271. };
  85272. DebugLayer.prototype.hide = function () {
  85273. if (this._inspector) {
  85274. try {
  85275. this._inspector.dispose();
  85276. }
  85277. catch (e) {
  85278. // If the inspector has been removed directly from the inspector tool
  85279. }
  85280. this._inspector = null;
  85281. }
  85282. };
  85283. DebugLayer.prototype.show = function (config) {
  85284. if (config === void 0) { config = {}; }
  85285. if (typeof this.BJSINSPECTOR == 'undefined') {
  85286. // Load inspector and add it to the DOM
  85287. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85288. }
  85289. else {
  85290. // Otherwise creates the inspector
  85291. this._createInspector(config);
  85292. }
  85293. };
  85294. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85295. return DebugLayer;
  85296. }());
  85297. BABYLON.DebugLayer = DebugLayer;
  85298. })(BABYLON || (BABYLON = {}));
  85299. //# sourceMappingURL=babylon.debugLayer.js.map
  85300. var BABYLON;
  85301. (function (BABYLON) {
  85302. var Debug;
  85303. (function (Debug) {
  85304. /**
  85305. * Used to show the physics impostor around the specific mesh.
  85306. */
  85307. var PhysicsViewer = /** @class */ (function () {
  85308. function PhysicsViewer(scene) {
  85309. this._impostors = [];
  85310. this._meshes = [];
  85311. this._numMeshes = 0;
  85312. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85313. var physicEngine = this._scene.getPhysicsEngine();
  85314. if (physicEngine) {
  85315. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85316. }
  85317. }
  85318. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85319. var plugin = this._physicsEnginePlugin;
  85320. for (var i = 0; i < this._numMeshes; i++) {
  85321. var impostor = this._impostors[i];
  85322. if (!impostor) {
  85323. continue;
  85324. }
  85325. if (impostor.isDisposed) {
  85326. this.hideImpostor(this._impostors[i--]);
  85327. }
  85328. else {
  85329. var mesh = this._meshes[i];
  85330. if (mesh && plugin) {
  85331. plugin.syncMeshWithImpostor(mesh, impostor);
  85332. }
  85333. }
  85334. }
  85335. };
  85336. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85337. if (!this._scene) {
  85338. return;
  85339. }
  85340. for (var i = 0; i < this._numMeshes; i++) {
  85341. if (this._impostors[i] == impostor) {
  85342. return;
  85343. }
  85344. }
  85345. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85346. if (debugMesh) {
  85347. this._impostors[this._numMeshes] = impostor;
  85348. this._meshes[this._numMeshes] = debugMesh;
  85349. if (this._numMeshes === 0) {
  85350. this._renderFunction = this._updateDebugMeshes.bind(this);
  85351. this._scene.registerBeforeRender(this._renderFunction);
  85352. }
  85353. this._numMeshes++;
  85354. }
  85355. };
  85356. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85357. if (!impostor || !this._scene) {
  85358. return;
  85359. }
  85360. var removed = false;
  85361. for (var i = 0; i < this._numMeshes; i++) {
  85362. if (this._impostors[i] == impostor) {
  85363. var mesh = this._meshes[i];
  85364. if (!mesh) {
  85365. continue;
  85366. }
  85367. this._scene.removeMesh(mesh);
  85368. mesh.dispose();
  85369. this._numMeshes--;
  85370. if (this._numMeshes > 0) {
  85371. this._meshes[i] = this._meshes[this._numMeshes];
  85372. this._impostors[i] = this._impostors[this._numMeshes];
  85373. this._meshes[this._numMeshes] = null;
  85374. this._impostors[this._numMeshes] = null;
  85375. }
  85376. else {
  85377. this._meshes[0] = null;
  85378. this._impostors[0] = null;
  85379. }
  85380. removed = true;
  85381. break;
  85382. }
  85383. }
  85384. if (removed && this._numMeshes === 0) {
  85385. this._scene.unregisterBeforeRender(this._renderFunction);
  85386. }
  85387. };
  85388. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85389. if (!this._debugMaterial) {
  85390. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85391. this._debugMaterial.wireframe = true;
  85392. }
  85393. return this._debugMaterial;
  85394. };
  85395. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85396. if (!this._debugBoxMesh) {
  85397. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85398. this._debugBoxMesh.renderingGroupId = 1;
  85399. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85400. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85401. scene.removeMesh(this._debugBoxMesh);
  85402. }
  85403. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85404. };
  85405. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85406. if (!this._debugSphereMesh) {
  85407. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85408. this._debugSphereMesh.renderingGroupId = 1;
  85409. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85410. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85411. scene.removeMesh(this._debugSphereMesh);
  85412. }
  85413. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85414. };
  85415. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85416. var mesh = null;
  85417. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85418. mesh = this._getDebugBoxMesh(scene);
  85419. impostor.getBoxSizeToRef(mesh.scaling);
  85420. }
  85421. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85422. mesh = this._getDebugSphereMesh(scene);
  85423. var radius = impostor.getRadius();
  85424. mesh.scaling.x = radius * 2;
  85425. mesh.scaling.y = radius * 2;
  85426. mesh.scaling.z = radius * 2;
  85427. }
  85428. return mesh;
  85429. };
  85430. PhysicsViewer.prototype.dispose = function () {
  85431. for (var i = 0; i < this._numMeshes; i++) {
  85432. this.hideImpostor(this._impostors[i]);
  85433. }
  85434. if (this._debugBoxMesh) {
  85435. this._debugBoxMesh.dispose();
  85436. }
  85437. if (this._debugSphereMesh) {
  85438. this._debugSphereMesh.dispose();
  85439. }
  85440. if (this._debugMaterial) {
  85441. this._debugMaterial.dispose();
  85442. }
  85443. this._impostors.length = 0;
  85444. this._scene = null;
  85445. this._physicsEnginePlugin = null;
  85446. };
  85447. return PhysicsViewer;
  85448. }());
  85449. Debug.PhysicsViewer = PhysicsViewer;
  85450. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85451. })(BABYLON || (BABYLON = {}));
  85452. //# sourceMappingURL=babylon.physicsViewer.js.map
  85453. var BABYLON;
  85454. (function (BABYLON) {
  85455. var BoundingBoxRenderer = /** @class */ (function () {
  85456. function BoundingBoxRenderer(scene) {
  85457. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85458. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85459. this.showBackLines = true;
  85460. this.renderList = new BABYLON.SmartArray(32);
  85461. this._vertexBuffers = {};
  85462. this._scene = scene;
  85463. }
  85464. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85465. if (this._colorShader) {
  85466. return;
  85467. }
  85468. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85469. attributes: [BABYLON.VertexBuffer.PositionKind],
  85470. uniforms: ["world", "viewProjection", "color"]
  85471. });
  85472. var engine = this._scene.getEngine();
  85473. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  85474. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  85475. this._createIndexBuffer();
  85476. };
  85477. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  85478. var engine = this._scene.getEngine();
  85479. 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]);
  85480. };
  85481. BoundingBoxRenderer.prototype._rebuild = function () {
  85482. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85483. if (vb) {
  85484. vb._rebuild();
  85485. }
  85486. this._createIndexBuffer();
  85487. };
  85488. BoundingBoxRenderer.prototype.reset = function () {
  85489. this.renderList.reset();
  85490. };
  85491. BoundingBoxRenderer.prototype.render = function () {
  85492. if (this.renderList.length === 0) {
  85493. return;
  85494. }
  85495. this._prepareRessources();
  85496. if (!this._colorShader.isReady()) {
  85497. return;
  85498. }
  85499. var engine = this._scene.getEngine();
  85500. engine.setDepthWrite(false);
  85501. this._colorShader._preBind();
  85502. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  85503. var boundingBox = this.renderList.data[boundingBoxIndex];
  85504. var min = boundingBox.minimum;
  85505. var max = boundingBox.maximum;
  85506. var diff = max.subtract(min);
  85507. var median = min.add(diff.scale(0.5));
  85508. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85509. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85510. .multiply(boundingBox.getWorldMatrix());
  85511. // VBOs
  85512. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85513. if (this.showBackLines) {
  85514. // Back
  85515. engine.setDepthFunctionToGreaterOrEqual();
  85516. this._scene.resetCachedMaterial();
  85517. this._colorShader.setColor4("color", this.backColor.toColor4());
  85518. this._colorShader.bind(worldMatrix);
  85519. // Draw order
  85520. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85521. }
  85522. // Front
  85523. engine.setDepthFunctionToLess();
  85524. this._scene.resetCachedMaterial();
  85525. this._colorShader.setColor4("color", this.frontColor.toColor4());
  85526. this._colorShader.bind(worldMatrix);
  85527. // Draw order
  85528. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85529. }
  85530. this._colorShader.unbind();
  85531. engine.setDepthFunctionToLessOrEqual();
  85532. engine.setDepthWrite(true);
  85533. };
  85534. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  85535. this._prepareRessources();
  85536. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  85537. return;
  85538. }
  85539. var engine = this._scene.getEngine();
  85540. engine.setDepthWrite(false);
  85541. engine.setColorWrite(false);
  85542. this._colorShader._preBind();
  85543. var boundingBox = mesh._boundingInfo.boundingBox;
  85544. var min = boundingBox.minimum;
  85545. var max = boundingBox.maximum;
  85546. var diff = max.subtract(min);
  85547. var median = min.add(diff.scale(0.5));
  85548. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85549. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85550. .multiply(boundingBox.getWorldMatrix());
  85551. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85552. engine.setDepthFunctionToLess();
  85553. this._scene.resetCachedMaterial();
  85554. this._colorShader.bind(worldMatrix);
  85555. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85556. this._colorShader.unbind();
  85557. engine.setDepthFunctionToLessOrEqual();
  85558. engine.setDepthWrite(true);
  85559. engine.setColorWrite(true);
  85560. };
  85561. BoundingBoxRenderer.prototype.dispose = function () {
  85562. if (!this._colorShader) {
  85563. return;
  85564. }
  85565. this.renderList.dispose();
  85566. this._colorShader.dispose();
  85567. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85568. if (buffer) {
  85569. buffer.dispose();
  85570. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85571. }
  85572. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85573. };
  85574. return BoundingBoxRenderer;
  85575. }());
  85576. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85577. })(BABYLON || (BABYLON = {}));
  85578. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85579. var BABYLON;
  85580. (function (BABYLON) {
  85581. /**
  85582. * Defines a target to use with MorphTargetManager
  85583. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85584. */
  85585. var MorphTarget = /** @class */ (function () {
  85586. /**
  85587. * Creates a new MorphTarget
  85588. * @param name defines the name of the target
  85589. * @param influence defines the influence to use
  85590. */
  85591. function MorphTarget(
  85592. /** defines the name of the target */
  85593. name, influence, scene) {
  85594. if (influence === void 0) { influence = 0; }
  85595. if (scene === void 0) { scene = null; }
  85596. this.name = name;
  85597. /**
  85598. * Gets or sets the list of animations
  85599. */
  85600. this.animations = new Array();
  85601. this._positions = null;
  85602. this._normals = null;
  85603. this._tangents = null;
  85604. /**
  85605. * Observable raised when the influence changes
  85606. */
  85607. this.onInfluenceChanged = new BABYLON.Observable();
  85608. this._animationPropertiesOverride = null;
  85609. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85610. this.influence = influence;
  85611. }
  85612. Object.defineProperty(MorphTarget.prototype, "influence", {
  85613. /**
  85614. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85615. */
  85616. get: function () {
  85617. return this._influence;
  85618. },
  85619. set: function (influence) {
  85620. if (this._influence === influence) {
  85621. return;
  85622. }
  85623. var previous = this._influence;
  85624. this._influence = influence;
  85625. if (this.onInfluenceChanged.hasObservers) {
  85626. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85627. }
  85628. },
  85629. enumerable: true,
  85630. configurable: true
  85631. });
  85632. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  85633. /**
  85634. * Gets or sets the animation properties override
  85635. */
  85636. get: function () {
  85637. if (!this._animationPropertiesOverride && this._scene) {
  85638. return this._scene.animationPropertiesOverride;
  85639. }
  85640. return this._animationPropertiesOverride;
  85641. },
  85642. set: function (value) {
  85643. this._animationPropertiesOverride = value;
  85644. },
  85645. enumerable: true,
  85646. configurable: true
  85647. });
  85648. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85649. /**
  85650. * Gets a boolean defining if the target contains position data
  85651. */
  85652. get: function () {
  85653. return !!this._positions;
  85654. },
  85655. enumerable: true,
  85656. configurable: true
  85657. });
  85658. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85659. /**
  85660. * Gets a boolean defining if the target contains normal data
  85661. */
  85662. get: function () {
  85663. return !!this._normals;
  85664. },
  85665. enumerable: true,
  85666. configurable: true
  85667. });
  85668. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85669. /**
  85670. * Gets a boolean defining if the target contains tangent data
  85671. */
  85672. get: function () {
  85673. return !!this._tangents;
  85674. },
  85675. enumerable: true,
  85676. configurable: true
  85677. });
  85678. /**
  85679. * Affects position data to this target
  85680. * @param data defines the position data to use
  85681. */
  85682. MorphTarget.prototype.setPositions = function (data) {
  85683. this._positions = data;
  85684. };
  85685. /**
  85686. * Gets the position data stored in this target
  85687. * @returns a FloatArray containing the position data (or null if not present)
  85688. */
  85689. MorphTarget.prototype.getPositions = function () {
  85690. return this._positions;
  85691. };
  85692. /**
  85693. * Affects normal data to this target
  85694. * @param data defines the normal data to use
  85695. */
  85696. MorphTarget.prototype.setNormals = function (data) {
  85697. this._normals = data;
  85698. };
  85699. /**
  85700. * Gets the normal data stored in this target
  85701. * @returns a FloatArray containing the normal data (or null if not present)
  85702. */
  85703. MorphTarget.prototype.getNormals = function () {
  85704. return this._normals;
  85705. };
  85706. /**
  85707. * Affects tangent data to this target
  85708. * @param data defines the tangent data to use
  85709. */
  85710. MorphTarget.prototype.setTangents = function (data) {
  85711. this._tangents = data;
  85712. };
  85713. /**
  85714. * Gets the tangent data stored in this target
  85715. * @returns a FloatArray containing the tangent data (or null if not present)
  85716. */
  85717. MorphTarget.prototype.getTangents = function () {
  85718. return this._tangents;
  85719. };
  85720. /**
  85721. * Serializes the current target into a Serialization object
  85722. * @returns the serialized object
  85723. */
  85724. MorphTarget.prototype.serialize = function () {
  85725. var serializationObject = {};
  85726. serializationObject.name = this.name;
  85727. serializationObject.influence = this.influence;
  85728. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85729. if (this.hasNormals) {
  85730. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85731. }
  85732. if (this.hasTangents) {
  85733. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85734. }
  85735. // Animations
  85736. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85737. return serializationObject;
  85738. };
  85739. // Statics
  85740. /**
  85741. * Creates a new target from serialized data
  85742. * @param serializationObject defines the serialized data to use
  85743. * @returns a new MorphTarget
  85744. */
  85745. MorphTarget.Parse = function (serializationObject) {
  85746. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85747. result.setPositions(serializationObject.positions);
  85748. if (serializationObject.normals) {
  85749. result.setNormals(serializationObject.normals);
  85750. }
  85751. if (serializationObject.tangents) {
  85752. result.setTangents(serializationObject.tangents);
  85753. }
  85754. // Animations
  85755. if (serializationObject.animations) {
  85756. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85757. var parsedAnimation = serializationObject.animations[animationIndex];
  85758. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85759. }
  85760. }
  85761. return result;
  85762. };
  85763. /**
  85764. * Creates a MorphTarget from mesh data
  85765. * @param mesh defines the source mesh
  85766. * @param name defines the name to use for the new target
  85767. * @param influence defines the influence to attach to the target
  85768. * @returns a new MorphTarget
  85769. */
  85770. MorphTarget.FromMesh = function (mesh, name, influence) {
  85771. if (!name) {
  85772. name = mesh.name;
  85773. }
  85774. var result = new MorphTarget(name, influence, mesh.getScene());
  85775. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85776. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85777. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85778. }
  85779. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85780. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85781. }
  85782. return result;
  85783. };
  85784. return MorphTarget;
  85785. }());
  85786. BABYLON.MorphTarget = MorphTarget;
  85787. })(BABYLON || (BABYLON = {}));
  85788. //# sourceMappingURL=babylon.morphTarget.js.map
  85789. var BABYLON;
  85790. (function (BABYLON) {
  85791. /**
  85792. * This class is used to deform meshes using morphing between different targets
  85793. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85794. */
  85795. var MorphTargetManager = /** @class */ (function () {
  85796. /**
  85797. * Creates a new MorphTargetManager
  85798. * @param scene defines the current scene
  85799. */
  85800. function MorphTargetManager(scene) {
  85801. if (scene === void 0) { scene = null; }
  85802. this._targets = new Array();
  85803. this._targetObservable = new Array();
  85804. this._activeTargets = new BABYLON.SmartArray(16);
  85805. this._supportsNormals = false;
  85806. this._supportsTangents = false;
  85807. this._vertexCount = 0;
  85808. this._uniqueId = 0;
  85809. this._tempInfluences = new Array();
  85810. if (!scene) {
  85811. scene = BABYLON.Engine.LastCreatedScene;
  85812. }
  85813. this._scene = scene;
  85814. if (this._scene) {
  85815. this._scene.morphTargetManagers.push(this);
  85816. this._uniqueId = this._scene.getUniqueId();
  85817. }
  85818. }
  85819. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85820. /**
  85821. * Gets the unique ID of this manager
  85822. */
  85823. get: function () {
  85824. return this._uniqueId;
  85825. },
  85826. enumerable: true,
  85827. configurable: true
  85828. });
  85829. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  85830. /**
  85831. * Gets the number of vertices handled by this manager
  85832. */
  85833. get: function () {
  85834. return this._vertexCount;
  85835. },
  85836. enumerable: true,
  85837. configurable: true
  85838. });
  85839. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  85840. /**
  85841. * Gets a boolean indicating if this manager supports morphing of normals
  85842. */
  85843. get: function () {
  85844. return this._supportsNormals;
  85845. },
  85846. enumerable: true,
  85847. configurable: true
  85848. });
  85849. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  85850. /**
  85851. * Gets a boolean indicating if this manager supports morphing of tangents
  85852. */
  85853. get: function () {
  85854. return this._supportsTangents;
  85855. },
  85856. enumerable: true,
  85857. configurable: true
  85858. });
  85859. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  85860. /**
  85861. * Gets the number of targets stored in this manager
  85862. */
  85863. get: function () {
  85864. return this._targets.length;
  85865. },
  85866. enumerable: true,
  85867. configurable: true
  85868. });
  85869. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  85870. /**
  85871. * Gets the number of influencers (ie. the number of targets with influences > 0)
  85872. */
  85873. get: function () {
  85874. return this._activeTargets.length;
  85875. },
  85876. enumerable: true,
  85877. configurable: true
  85878. });
  85879. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  85880. /**
  85881. * Gets the list of influences (one per target)
  85882. */
  85883. get: function () {
  85884. return this._influences;
  85885. },
  85886. enumerable: true,
  85887. configurable: true
  85888. });
  85889. /**
  85890. * Gets the active target at specified index. An active target is a target with an influence > 0
  85891. * @param index defines the index to check
  85892. * @returns the requested target
  85893. */
  85894. MorphTargetManager.prototype.getActiveTarget = function (index) {
  85895. return this._activeTargets.data[index];
  85896. };
  85897. /**
  85898. * Gets the target at specified index
  85899. * @param index defines the index to check
  85900. * @returns the requested target
  85901. */
  85902. MorphTargetManager.prototype.getTarget = function (index) {
  85903. return this._targets[index];
  85904. };
  85905. /**
  85906. * Add a new target to this manager
  85907. * @param target defines the target to add
  85908. */
  85909. MorphTargetManager.prototype.addTarget = function (target) {
  85910. var _this = this;
  85911. this._targets.push(target);
  85912. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  85913. _this._syncActiveTargets(needUpdate);
  85914. }));
  85915. this._syncActiveTargets(true);
  85916. };
  85917. /**
  85918. * Removes a target from the manager
  85919. * @param target defines the target to remove
  85920. */
  85921. MorphTargetManager.prototype.removeTarget = function (target) {
  85922. var index = this._targets.indexOf(target);
  85923. if (index >= 0) {
  85924. this._targets.splice(index, 1);
  85925. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  85926. this._syncActiveTargets(true);
  85927. }
  85928. };
  85929. /**
  85930. * Serializes the current manager into a Serialization object
  85931. * @returns the serialized object
  85932. */
  85933. MorphTargetManager.prototype.serialize = function () {
  85934. var serializationObject = {};
  85935. serializationObject.id = this.uniqueId;
  85936. serializationObject.targets = [];
  85937. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85938. var target = _a[_i];
  85939. serializationObject.targets.push(target.serialize());
  85940. }
  85941. return serializationObject;
  85942. };
  85943. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  85944. var influenceCount = 0;
  85945. this._activeTargets.reset();
  85946. this._supportsNormals = true;
  85947. this._supportsTangents = true;
  85948. this._vertexCount = 0;
  85949. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85950. var target = _a[_i];
  85951. this._activeTargets.push(target);
  85952. this._tempInfluences[influenceCount++] = target.influence;
  85953. var positions = target.getPositions();
  85954. if (positions) {
  85955. this._supportsNormals = this._supportsNormals && target.hasNormals;
  85956. this._supportsTangents = this._supportsTangents && target.hasTangents;
  85957. var vertexCount = positions.length / 3;
  85958. if (this._vertexCount === 0) {
  85959. this._vertexCount = vertexCount;
  85960. }
  85961. else if (this._vertexCount !== vertexCount) {
  85962. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  85963. return;
  85964. }
  85965. }
  85966. }
  85967. if (!this._influences || this._influences.length !== influenceCount) {
  85968. this._influences = new Float32Array(influenceCount);
  85969. }
  85970. for (var index = 0; index < influenceCount; index++) {
  85971. this._influences[index] = this._tempInfluences[index];
  85972. }
  85973. if (needUpdate) {
  85974. this.synchronize();
  85975. }
  85976. };
  85977. /**
  85978. * Syncrhonize the targets with all the meshes using this morph target manager
  85979. */
  85980. MorphTargetManager.prototype.synchronize = function () {
  85981. if (!this._scene) {
  85982. return;
  85983. }
  85984. // Flag meshes as dirty to resync with the active targets
  85985. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  85986. var mesh = _a[_i];
  85987. if (mesh.morphTargetManager === this) {
  85988. mesh._syncGeometryWithMorphTargetManager();
  85989. }
  85990. }
  85991. };
  85992. // Statics
  85993. /**
  85994. * Creates a new MorphTargetManager from serialized data
  85995. * @param serializationObject defines the serialized data
  85996. * @param scene defines the hosting scene
  85997. * @returns the new MorphTargetManager
  85998. */
  85999. MorphTargetManager.Parse = function (serializationObject, scene) {
  86000. var result = new MorphTargetManager(scene);
  86001. result._uniqueId = serializationObject.id;
  86002. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  86003. var targetData = _a[_i];
  86004. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  86005. }
  86006. return result;
  86007. };
  86008. return MorphTargetManager;
  86009. }());
  86010. BABYLON.MorphTargetManager = MorphTargetManager;
  86011. })(BABYLON || (BABYLON = {}));
  86012. //# sourceMappingURL=babylon.morphTargetManager.js.map
  86013. var BABYLON;
  86014. (function (BABYLON) {
  86015. var Octree = /** @class */ (function () {
  86016. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  86017. if (maxDepth === void 0) { maxDepth = 2; }
  86018. this.maxDepth = maxDepth;
  86019. this.dynamicContent = new Array();
  86020. this._maxBlockCapacity = maxBlockCapacity || 64;
  86021. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  86022. this._creationFunc = creationFunc;
  86023. }
  86024. // Methods
  86025. Octree.prototype.update = function (worldMin, worldMax, entries) {
  86026. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  86027. };
  86028. Octree.prototype.addMesh = function (entry) {
  86029. for (var index = 0; index < this.blocks.length; index++) {
  86030. var block = this.blocks[index];
  86031. block.addEntry(entry);
  86032. }
  86033. };
  86034. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  86035. this._selectionContent.reset();
  86036. for (var index = 0; index < this.blocks.length; index++) {
  86037. var block = this.blocks[index];
  86038. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  86039. }
  86040. if (allowDuplicate) {
  86041. this._selectionContent.concat(this.dynamicContent);
  86042. }
  86043. else {
  86044. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86045. }
  86046. return this._selectionContent;
  86047. };
  86048. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  86049. this._selectionContent.reset();
  86050. for (var index = 0; index < this.blocks.length; index++) {
  86051. var block = this.blocks[index];
  86052. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  86053. }
  86054. if (allowDuplicate) {
  86055. this._selectionContent.concat(this.dynamicContent);
  86056. }
  86057. else {
  86058. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86059. }
  86060. return this._selectionContent;
  86061. };
  86062. Octree.prototype.intersectsRay = function (ray) {
  86063. this._selectionContent.reset();
  86064. for (var index = 0; index < this.blocks.length; index++) {
  86065. var block = this.blocks[index];
  86066. block.intersectsRay(ray, this._selectionContent);
  86067. }
  86068. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86069. return this._selectionContent;
  86070. };
  86071. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  86072. target.blocks = new Array();
  86073. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  86074. // Segmenting space
  86075. for (var x = 0; x < 2; x++) {
  86076. for (var y = 0; y < 2; y++) {
  86077. for (var z = 0; z < 2; z++) {
  86078. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  86079. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  86080. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  86081. block.addEntries(entries);
  86082. target.blocks.push(block);
  86083. }
  86084. }
  86085. }
  86086. };
  86087. Octree.CreationFuncForMeshes = function (entry, block) {
  86088. var boundingInfo = entry.getBoundingInfo();
  86089. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86090. block.entries.push(entry);
  86091. }
  86092. };
  86093. Octree.CreationFuncForSubMeshes = function (entry, block) {
  86094. var boundingInfo = entry.getBoundingInfo();
  86095. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86096. block.entries.push(entry);
  86097. }
  86098. };
  86099. return Octree;
  86100. }());
  86101. BABYLON.Octree = Octree;
  86102. })(BABYLON || (BABYLON = {}));
  86103. //# sourceMappingURL=babylon.octree.js.map
  86104. var BABYLON;
  86105. (function (BABYLON) {
  86106. var OctreeBlock = /** @class */ (function () {
  86107. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  86108. this.entries = new Array();
  86109. this._boundingVectors = new Array();
  86110. this._capacity = capacity;
  86111. this._depth = depth;
  86112. this._maxDepth = maxDepth;
  86113. this._creationFunc = creationFunc;
  86114. this._minPoint = minPoint;
  86115. this._maxPoint = maxPoint;
  86116. this._boundingVectors.push(minPoint.clone());
  86117. this._boundingVectors.push(maxPoint.clone());
  86118. this._boundingVectors.push(minPoint.clone());
  86119. this._boundingVectors[2].x = maxPoint.x;
  86120. this._boundingVectors.push(minPoint.clone());
  86121. this._boundingVectors[3].y = maxPoint.y;
  86122. this._boundingVectors.push(minPoint.clone());
  86123. this._boundingVectors[4].z = maxPoint.z;
  86124. this._boundingVectors.push(maxPoint.clone());
  86125. this._boundingVectors[5].z = minPoint.z;
  86126. this._boundingVectors.push(maxPoint.clone());
  86127. this._boundingVectors[6].x = minPoint.x;
  86128. this._boundingVectors.push(maxPoint.clone());
  86129. this._boundingVectors[7].y = minPoint.y;
  86130. }
  86131. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86132. // Property
  86133. get: function () {
  86134. return this._capacity;
  86135. },
  86136. enumerable: true,
  86137. configurable: true
  86138. });
  86139. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86140. get: function () {
  86141. return this._minPoint;
  86142. },
  86143. enumerable: true,
  86144. configurable: true
  86145. });
  86146. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86147. get: function () {
  86148. return this._maxPoint;
  86149. },
  86150. enumerable: true,
  86151. configurable: true
  86152. });
  86153. // Methods
  86154. OctreeBlock.prototype.addEntry = function (entry) {
  86155. if (this.blocks) {
  86156. for (var index = 0; index < this.blocks.length; index++) {
  86157. var block = this.blocks[index];
  86158. block.addEntry(entry);
  86159. }
  86160. return;
  86161. }
  86162. this._creationFunc(entry, this);
  86163. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86164. this.createInnerBlocks();
  86165. }
  86166. };
  86167. OctreeBlock.prototype.addEntries = function (entries) {
  86168. for (var index = 0; index < entries.length; index++) {
  86169. var mesh = entries[index];
  86170. this.addEntry(mesh);
  86171. }
  86172. };
  86173. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86174. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86175. if (this.blocks) {
  86176. for (var index = 0; index < this.blocks.length; index++) {
  86177. var block = this.blocks[index];
  86178. block.select(frustumPlanes, selection, allowDuplicate);
  86179. }
  86180. return;
  86181. }
  86182. if (allowDuplicate) {
  86183. selection.concat(this.entries);
  86184. }
  86185. else {
  86186. selection.concatWithNoDuplicate(this.entries);
  86187. }
  86188. }
  86189. };
  86190. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86191. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86192. if (this.blocks) {
  86193. for (var index = 0; index < this.blocks.length; index++) {
  86194. var block = this.blocks[index];
  86195. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86196. }
  86197. return;
  86198. }
  86199. if (allowDuplicate) {
  86200. selection.concat(this.entries);
  86201. }
  86202. else {
  86203. selection.concatWithNoDuplicate(this.entries);
  86204. }
  86205. }
  86206. };
  86207. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86208. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86209. if (this.blocks) {
  86210. for (var index = 0; index < this.blocks.length; index++) {
  86211. var block = this.blocks[index];
  86212. block.intersectsRay(ray, selection);
  86213. }
  86214. return;
  86215. }
  86216. selection.concatWithNoDuplicate(this.entries);
  86217. }
  86218. };
  86219. OctreeBlock.prototype.createInnerBlocks = function () {
  86220. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86221. };
  86222. return OctreeBlock;
  86223. }());
  86224. BABYLON.OctreeBlock = OctreeBlock;
  86225. })(BABYLON || (BABYLON = {}));
  86226. //# sourceMappingURL=babylon.octreeBlock.js.map
  86227. var BABYLON;
  86228. (function (BABYLON) {
  86229. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86230. __extends(VRDistortionCorrectionPostProcess, _super);
  86231. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86232. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86233. 'LensCenter',
  86234. 'Scale',
  86235. 'ScaleIn',
  86236. 'HmdWarpParam'
  86237. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86238. _this._isRightEye = isRightEye;
  86239. _this._distortionFactors = vrMetrics.distortionK;
  86240. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86241. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86242. _this.adaptScaleToCurrentViewport = true;
  86243. _this.onSizeChangedObservable.add(function () {
  86244. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86245. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86246. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86247. });
  86248. _this.onApplyObservable.add(function (effect) {
  86249. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86250. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86251. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86252. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86253. });
  86254. return _this;
  86255. }
  86256. return VRDistortionCorrectionPostProcess;
  86257. }(BABYLON.PostProcess));
  86258. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86259. })(BABYLON || (BABYLON = {}));
  86260. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86261. var BABYLON;
  86262. (function (BABYLON) {
  86263. /**
  86264. * Postprocess used to generate anaglyphic rendering
  86265. */
  86266. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86267. __extends(AnaglyphPostProcess, _super);
  86268. /**
  86269. * Creates a new AnaglyphPostProcess
  86270. * @param name defines postprocess name
  86271. * @param options defines creation options or target ratio scale
  86272. * @param rigCameras defines cameras using this postprocess
  86273. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86274. * @param engine defines hosting engine
  86275. * @param reusable defines if the postprocess will be reused multiple times per frame
  86276. */
  86277. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86278. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86279. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86280. _this.onApplyObservable.add(function (effect) {
  86281. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86282. });
  86283. return _this;
  86284. }
  86285. return AnaglyphPostProcess;
  86286. }(BABYLON.PostProcess));
  86287. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86288. })(BABYLON || (BABYLON = {}));
  86289. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86290. var BABYLON;
  86291. (function (BABYLON) {
  86292. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86293. __extends(StereoscopicInterlacePostProcess, _super);
  86294. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86295. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86296. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86297. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86298. _this.onSizeChangedObservable.add(function () {
  86299. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86300. });
  86301. _this.onApplyObservable.add(function (effect) {
  86302. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86303. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86304. });
  86305. return _this;
  86306. }
  86307. return StereoscopicInterlacePostProcess;
  86308. }(BABYLON.PostProcess));
  86309. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86310. })(BABYLON || (BABYLON = {}));
  86311. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86312. var BABYLON;
  86313. (function (BABYLON) {
  86314. /**
  86315. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86316. * Screen rotation is taken into account.
  86317. */
  86318. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86319. function FreeCameraDeviceOrientationInput() {
  86320. var _this = this;
  86321. this._screenOrientationAngle = 0;
  86322. this._screenQuaternion = new BABYLON.Quaternion();
  86323. this._alpha = 0;
  86324. this._beta = 0;
  86325. this._gamma = 0;
  86326. this._orientationChanged = function () {
  86327. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86328. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86329. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86330. };
  86331. this._deviceOrientation = function (evt) {
  86332. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86333. _this._beta = evt.beta !== null ? evt.beta : 0;
  86334. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86335. };
  86336. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86337. this._orientationChanged();
  86338. }
  86339. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86340. get: function () {
  86341. return this._camera;
  86342. },
  86343. set: function (camera) {
  86344. this._camera = camera;
  86345. if (this._camera != null && !this._camera.rotationQuaternion) {
  86346. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  86347. }
  86348. },
  86349. enumerable: true,
  86350. configurable: true
  86351. });
  86352. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86353. window.addEventListener("orientationchange", this._orientationChanged);
  86354. window.addEventListener("deviceorientation", this._deviceOrientation);
  86355. //In certain cases, the attach control is called AFTER orientation was changed,
  86356. //So this is needed.
  86357. this._orientationChanged();
  86358. };
  86359. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  86360. window.removeEventListener("orientationchange", this._orientationChanged);
  86361. window.removeEventListener("deviceorientation", this._deviceOrientation);
  86362. };
  86363. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  86364. //if no device orientation provided, don't update the rotation.
  86365. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  86366. if (!this._alpha)
  86367. return;
  86368. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  86369. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  86370. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  86371. //Mirror on XY Plane
  86372. this._camera.rotationQuaternion.z *= -1;
  86373. this._camera.rotationQuaternion.w *= -1;
  86374. };
  86375. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  86376. return "FreeCameraDeviceOrientationInput";
  86377. };
  86378. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  86379. return "deviceOrientation";
  86380. };
  86381. return FreeCameraDeviceOrientationInput;
  86382. }());
  86383. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  86384. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  86385. })(BABYLON || (BABYLON = {}));
  86386. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  86387. var BABYLON;
  86388. (function (BABYLON) {
  86389. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  86390. function ArcRotateCameraVRDeviceOrientationInput() {
  86391. this.alphaCorrection = 1;
  86392. this.betaCorrection = 1;
  86393. this.gammaCorrection = 1;
  86394. this._alpha = 0;
  86395. this._gamma = 0;
  86396. this._dirty = false;
  86397. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  86398. }
  86399. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86400. this.camera.attachControl(element, noPreventDefault);
  86401. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  86402. };
  86403. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  86404. if (evt.alpha !== null) {
  86405. this._alpha = +evt.alpha | 0;
  86406. }
  86407. if (evt.gamma !== null) {
  86408. this._gamma = +evt.gamma | 0;
  86409. }
  86410. this._dirty = true;
  86411. };
  86412. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  86413. if (this._dirty) {
  86414. this._dirty = false;
  86415. if (this._gamma < 0) {
  86416. this._gamma = 180 + this._gamma;
  86417. }
  86418. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  86419. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  86420. }
  86421. };
  86422. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  86423. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  86424. };
  86425. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  86426. return "ArcRotateCameraVRDeviceOrientationInput";
  86427. };
  86428. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  86429. return "VRDeviceOrientation";
  86430. };
  86431. return ArcRotateCameraVRDeviceOrientationInput;
  86432. }());
  86433. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  86434. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  86435. })(BABYLON || (BABYLON = {}));
  86436. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  86437. var BABYLON;
  86438. (function (BABYLON) {
  86439. var VRCameraMetrics = /** @class */ (function () {
  86440. function VRCameraMetrics() {
  86441. this.compensateDistortion = true;
  86442. }
  86443. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  86444. get: function () {
  86445. return this.hResolution / (2 * this.vResolution);
  86446. },
  86447. enumerable: true,
  86448. configurable: true
  86449. });
  86450. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  86451. get: function () {
  86452. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  86453. },
  86454. enumerable: true,
  86455. configurable: true
  86456. });
  86457. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  86458. get: function () {
  86459. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86460. var h = (4 * meters) / this.hScreenSize;
  86461. return BABYLON.Matrix.Translation(h, 0, 0);
  86462. },
  86463. enumerable: true,
  86464. configurable: true
  86465. });
  86466. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  86467. get: function () {
  86468. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86469. var h = (4 * meters) / this.hScreenSize;
  86470. return BABYLON.Matrix.Translation(-h, 0, 0);
  86471. },
  86472. enumerable: true,
  86473. configurable: true
  86474. });
  86475. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  86476. get: function () {
  86477. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  86478. },
  86479. enumerable: true,
  86480. configurable: true
  86481. });
  86482. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  86483. get: function () {
  86484. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  86485. },
  86486. enumerable: true,
  86487. configurable: true
  86488. });
  86489. VRCameraMetrics.GetDefault = function () {
  86490. var result = new VRCameraMetrics();
  86491. result.hResolution = 1280;
  86492. result.vResolution = 800;
  86493. result.hScreenSize = 0.149759993;
  86494. result.vScreenSize = 0.0935999975;
  86495. result.vScreenCenter = 0.0467999987;
  86496. result.eyeToScreenDistance = 0.0410000011;
  86497. result.lensSeparationDistance = 0.0635000020;
  86498. result.interpupillaryDistance = 0.0640000030;
  86499. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  86500. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  86501. result.postProcessScaleFactor = 1.714605507808412;
  86502. result.lensCenterOffset = 0.151976421;
  86503. return result;
  86504. };
  86505. return VRCameraMetrics;
  86506. }());
  86507. BABYLON.VRCameraMetrics = VRCameraMetrics;
  86508. })(BABYLON || (BABYLON = {}));
  86509. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  86510. var BABYLON;
  86511. (function (BABYLON) {
  86512. /**
  86513. * This represents a WebVR camera.
  86514. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  86515. * @example http://doc.babylonjs.com/how_to/webvr_camera
  86516. */
  86517. var WebVRFreeCamera = /** @class */ (function (_super) {
  86518. __extends(WebVRFreeCamera, _super);
  86519. /**
  86520. * Instantiates a WebVRFreeCamera.
  86521. * @param name The name of the WebVRFreeCamera
  86522. * @param position The starting anchor position for the camera
  86523. * @param scene The scene the camera belongs to
  86524. * @param webVROptions a set of customizable options for the webVRCamera
  86525. */
  86526. function WebVRFreeCamera(name, position, scene, webVROptions) {
  86527. if (webVROptions === void 0) { webVROptions = {}; }
  86528. var _this = _super.call(this, name, position, scene) || this;
  86529. _this.webVROptions = webVROptions;
  86530. /**
  86531. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  86532. */
  86533. _this._vrDevice = null;
  86534. /**
  86535. * The rawPose of the vrDevice.
  86536. */
  86537. _this.rawPose = null;
  86538. _this._specsVersion = "1.1";
  86539. _this._attached = false;
  86540. _this._descendants = [];
  86541. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  86542. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  86543. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  86544. _this._standingMatrix = null;
  86545. /**
  86546. * Represents device position in babylon space.
  86547. */
  86548. _this.devicePosition = BABYLON.Vector3.Zero();
  86549. /**
  86550. * Represents device rotation in babylon space.
  86551. */
  86552. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  86553. /**
  86554. * The scale of the device to be used when translating from device space to babylon space.
  86555. */
  86556. _this.deviceScaleFactor = 1;
  86557. _this._deviceToWorld = BABYLON.Matrix.Identity();
  86558. _this._worldToDevice = BABYLON.Matrix.Identity();
  86559. /**
  86560. * References to the webVR controllers for the vrDevice.
  86561. */
  86562. _this.controllers = [];
  86563. /**
  86564. * Emits an event when a controller is attached.
  86565. */
  86566. _this.onControllersAttachedObservable = new BABYLON.Observable();
  86567. /**
  86568. * Emits an event when a controller's mesh has been loaded;
  86569. */
  86570. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86571. /**
  86572. * If the rig cameras be used as parent instead of this camera.
  86573. */
  86574. _this.rigParenting = true;
  86575. _this._defaultHeight = undefined;
  86576. _this._workingVector = BABYLON.Vector3.Zero();
  86577. _this._oneVector = BABYLON.Vector3.One();
  86578. _this._workingMatrix = BABYLON.Matrix.Identity();
  86579. _this._cache.position = BABYLON.Vector3.Zero();
  86580. if (webVROptions.defaultHeight) {
  86581. _this._defaultHeight = webVROptions.defaultHeight;
  86582. _this.position.y = _this._defaultHeight;
  86583. }
  86584. _this.minZ = 0.1;
  86585. //legacy support - the compensation boolean was removed.
  86586. if (arguments.length === 5) {
  86587. _this.webVROptions = arguments[4];
  86588. }
  86589. // default webVR options
  86590. if (_this.webVROptions.trackPosition == undefined) {
  86591. _this.webVROptions.trackPosition = true;
  86592. }
  86593. if (_this.webVROptions.controllerMeshes == undefined) {
  86594. _this.webVROptions.controllerMeshes = true;
  86595. }
  86596. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86597. _this.webVROptions.defaultLightingOnControllers = true;
  86598. }
  86599. _this.rotationQuaternion = new BABYLON.Quaternion();
  86600. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86601. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86602. }
  86603. //enable VR
  86604. var engine = _this.getEngine();
  86605. _this._onVREnabled = function (success) { if (success) {
  86606. _this.initControllers();
  86607. } };
  86608. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86609. engine.initWebVR().add(function (event) {
  86610. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86611. return;
  86612. }
  86613. _this._vrDevice = event.vrDisplay;
  86614. //reset the rig parameters.
  86615. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86616. if (_this._attached) {
  86617. _this.getEngine().enableVR();
  86618. }
  86619. });
  86620. if (typeof (VRFrameData) !== "undefined")
  86621. _this._frameData = new VRFrameData();
  86622. /**
  86623. * The idea behind the following lines:
  86624. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86625. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86626. * the second will not show it correctly.
  86627. *
  86628. * To solve this - each object that has the camera as parent will be added to a protected array.
  86629. * When the rig camera renders, it will take this array and set all of those to be its children.
  86630. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86631. * Amazing!
  86632. */
  86633. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86634. if (camera.parent === _this && _this.rigParenting) {
  86635. _this._descendants = _this.getDescendants(true, function (n) {
  86636. // don't take the cameras or the controllers!
  86637. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86638. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86639. return !isController && !isRigCamera;
  86640. });
  86641. _this._descendants.forEach(function (node) {
  86642. node.parent = camera;
  86643. });
  86644. }
  86645. });
  86646. scene.onAfterCameraRenderObservable.add(function (camera) {
  86647. if (camera.parent === _this && _this.rigParenting) {
  86648. _this._descendants.forEach(function (node) {
  86649. node.parent = _this;
  86650. });
  86651. }
  86652. });
  86653. return _this;
  86654. }
  86655. /**
  86656. * Gets the device distance from the ground in meters.
  86657. * @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.
  86658. */
  86659. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86660. if (this._standingMatrix) {
  86661. // Add standing matrix offset to get real offset from ground in room
  86662. this._standingMatrix.getTranslationToRef(this._workingVector);
  86663. return this._deviceRoomPosition.y + this._workingVector.y;
  86664. }
  86665. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86666. return this._defaultHeight || 0;
  86667. };
  86668. /**
  86669. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86670. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86671. */
  86672. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86673. var _this = this;
  86674. if (callback === void 0) { callback = function (bool) { }; }
  86675. // Use standing matrix if available
  86676. this.getEngine().initWebVRAsync().then(function (result) {
  86677. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86678. callback(false);
  86679. }
  86680. else {
  86681. _this._standingMatrix = new BABYLON.Matrix();
  86682. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86683. if (!_this.getScene().useRightHandedSystem) {
  86684. [2, 6, 8, 9, 14].forEach(function (num) {
  86685. if (_this._standingMatrix) {
  86686. _this._standingMatrix.m[num] *= -1;
  86687. }
  86688. });
  86689. }
  86690. callback(true);
  86691. }
  86692. });
  86693. };
  86694. /**
  86695. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86696. * @returns A promise with a boolean set to if the standing matrix is supported.
  86697. */
  86698. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86699. var _this = this;
  86700. return new Promise(function (res, rej) {
  86701. _this.useStandingMatrix(function (supported) {
  86702. res(supported);
  86703. });
  86704. });
  86705. };
  86706. /**
  86707. * Disposes the camera
  86708. */
  86709. WebVRFreeCamera.prototype.dispose = function () {
  86710. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86711. _super.prototype.dispose.call(this);
  86712. };
  86713. /**
  86714. * Gets a vrController by name.
  86715. * @param name The name of the controller to retreive
  86716. * @returns the controller matching the name specified or null if not found
  86717. */
  86718. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86719. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86720. var gp = _a[_i];
  86721. if (gp.hand === name) {
  86722. return gp;
  86723. }
  86724. }
  86725. return null;
  86726. };
  86727. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86728. /**
  86729. * The controller corrisponding to the users left hand.
  86730. */
  86731. get: function () {
  86732. if (!this._leftController) {
  86733. this._leftController = this.getControllerByName("left");
  86734. }
  86735. return this._leftController;
  86736. },
  86737. enumerable: true,
  86738. configurable: true
  86739. });
  86740. ;
  86741. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86742. /**
  86743. * The controller corrisponding to the users right hand.
  86744. */
  86745. get: function () {
  86746. if (!this._rightController) {
  86747. this._rightController = this.getControllerByName("right");
  86748. }
  86749. return this._rightController;
  86750. },
  86751. enumerable: true,
  86752. configurable: true
  86753. });
  86754. ;
  86755. /**
  86756. * Casts a ray forward from the vrCamera's gaze.
  86757. * @param length Length of the ray (default: 100)
  86758. * @returns the ray corrisponding to the gaze
  86759. */
  86760. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86761. if (length === void 0) { length = 100; }
  86762. if (this.leftCamera) {
  86763. // Use left eye to avoid computation to compute center on every call
  86764. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86765. }
  86766. else {
  86767. return _super.prototype.getForwardRay.call(this, length);
  86768. }
  86769. };
  86770. /**
  86771. * Updates the camera based on device's frame data
  86772. */
  86773. WebVRFreeCamera.prototype._checkInputs = function () {
  86774. if (this._vrDevice && this._vrDevice.isPresenting) {
  86775. this._vrDevice.getFrameData(this._frameData);
  86776. this.updateFromDevice(this._frameData.pose);
  86777. }
  86778. _super.prototype._checkInputs.call(this);
  86779. };
  86780. /**
  86781. * Updates the poseControlled values based on the input device pose.
  86782. * @param poseData Pose coming from the device
  86783. */
  86784. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86785. if (poseData && poseData.orientation) {
  86786. this.rawPose = poseData;
  86787. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86788. if (this.getScene().useRightHandedSystem) {
  86789. this._deviceRoomRotationQuaternion.z *= -1;
  86790. this._deviceRoomRotationQuaternion.w *= -1;
  86791. }
  86792. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86793. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86794. if (this.getScene().useRightHandedSystem) {
  86795. this._deviceRoomPosition.z *= -1;
  86796. }
  86797. }
  86798. }
  86799. };
  86800. /**
  86801. * WebVR's attach control will start broadcasting frames to the device.
  86802. * Note that in certain browsers (chrome for example) this function must be called
  86803. * within a user-interaction callback. Example:
  86804. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86805. *
  86806. * @param element html element to attach the vrDevice to
  86807. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86808. */
  86809. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86810. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86811. this._attached = true;
  86812. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86813. if (this._vrDevice) {
  86814. this.getEngine().enableVR();
  86815. }
  86816. };
  86817. /**
  86818. * Detaches the camera from the html element and disables VR
  86819. *
  86820. * @param element html element to detach from
  86821. */
  86822. WebVRFreeCamera.prototype.detachControl = function (element) {
  86823. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86824. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86825. _super.prototype.detachControl.call(this, element);
  86826. this._attached = false;
  86827. this.getEngine().disableVR();
  86828. };
  86829. /**
  86830. * @returns the name of this class
  86831. */
  86832. WebVRFreeCamera.prototype.getClassName = function () {
  86833. return "WebVRFreeCamera";
  86834. };
  86835. /**
  86836. * Calls resetPose on the vrDisplay
  86837. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  86838. */
  86839. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  86840. //uses the vrDisplay's "resetPose()".
  86841. //pitch and roll won't be affected.
  86842. this._vrDevice.resetPose();
  86843. };
  86844. /**
  86845. * Updates the rig cameras (left and right eye)
  86846. */
  86847. WebVRFreeCamera.prototype._updateRigCameras = function () {
  86848. var camLeft = this._rigCameras[0];
  86849. var camRight = this._rigCameras[1];
  86850. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86851. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86852. camLeft.position.copyFrom(this._deviceRoomPosition);
  86853. camRight.position.copyFrom(this._deviceRoomPosition);
  86854. };
  86855. /**
  86856. * Updates the cached values of the camera
  86857. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  86858. */
  86859. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  86860. var _this = this;
  86861. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  86862. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  86863. if (!this.updateCacheCalled) {
  86864. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  86865. this.updateCacheCalled = true;
  86866. this.update();
  86867. }
  86868. // Set working vector to the device position in room space rotated by the new rotation
  86869. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  86870. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  86871. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  86872. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  86873. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  86874. // Add translation from anchor position
  86875. this._deviceToWorld.getTranslationToRef(this._workingVector);
  86876. this._workingVector.addInPlace(this.position);
  86877. this._workingVector.subtractInPlace(this._cache.position);
  86878. this._deviceToWorld.setTranslation(this._workingVector);
  86879. // Set an inverted matrix to be used when updating the camera
  86880. this._deviceToWorld.invertToRef(this._worldToDevice);
  86881. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  86882. this.controllers.forEach(function (controller) {
  86883. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  86884. controller.update();
  86885. });
  86886. }
  86887. if (!ignoreParentClass) {
  86888. _super.prototype._updateCache.call(this);
  86889. }
  86890. this.updateCacheCalled = false;
  86891. };
  86892. /**
  86893. * Updates the current device position and rotation in the babylon world
  86894. */
  86895. WebVRFreeCamera.prototype.update = function () {
  86896. // Get current device position in babylon world
  86897. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  86898. // Get current device rotation in babylon world
  86899. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  86900. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  86901. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  86902. _super.prototype.update.call(this);
  86903. };
  86904. /**
  86905. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  86906. * @returns an identity matrix
  86907. */
  86908. WebVRFreeCamera.prototype._getViewMatrix = function () {
  86909. return BABYLON.Matrix.Identity();
  86910. };
  86911. /**
  86912. * This function is called by the two RIG cameras.
  86913. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  86914. */
  86915. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  86916. var _this = this;
  86917. // Update the parent camera prior to using a child camera to avoid desynchronization
  86918. var parentCamera = this._cameraRigParams["parentCamera"];
  86919. parentCamera._updateCache();
  86920. //WebVR 1.1
  86921. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  86922. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  86923. if (!this.getScene().useRightHandedSystem) {
  86924. [2, 6, 8, 9, 14].forEach(function (num) {
  86925. _this._webvrViewMatrix.m[num] *= -1;
  86926. });
  86927. }
  86928. // update the camera rotation matrix
  86929. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  86930. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  86931. // Computing target and final matrix
  86932. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  86933. // should the view matrix be updated with scale and position offset?
  86934. if (parentCamera.deviceScaleFactor !== 1) {
  86935. this._webvrViewMatrix.invert();
  86936. // scale the position, if set
  86937. if (parentCamera.deviceScaleFactor) {
  86938. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  86939. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  86940. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  86941. }
  86942. this._webvrViewMatrix.invert();
  86943. }
  86944. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  86945. // Compute global position
  86946. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  86947. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  86948. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  86949. this._workingMatrix.getTranslationToRef(this._globalPosition);
  86950. this._markSyncedWithParent();
  86951. return this._webvrViewMatrix;
  86952. };
  86953. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  86954. var _this = this;
  86955. var parentCamera = this.parent;
  86956. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  86957. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  86958. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  86959. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  86960. //babylon compatible matrix
  86961. if (!this.getScene().useRightHandedSystem) {
  86962. [8, 9, 10, 11].forEach(function (num) {
  86963. _this._projectionMatrix.m[num] *= -1;
  86964. });
  86965. }
  86966. return this._projectionMatrix;
  86967. };
  86968. /**
  86969. * Initializes the controllers and their meshes
  86970. */
  86971. WebVRFreeCamera.prototype.initControllers = function () {
  86972. var _this = this;
  86973. this.controllers = [];
  86974. var manager = this.getScene().gamepadManager;
  86975. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  86976. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86977. var webVrController = gamepad;
  86978. if (webVrController.defaultModel) {
  86979. webVrController.defaultModel.setEnabled(false);
  86980. }
  86981. if (webVrController.hand === "right") {
  86982. _this._rightController = null;
  86983. }
  86984. if (webVrController.hand === "left") {
  86985. _this._leftController = null;
  86986. }
  86987. var controllerIndex = _this.controllers.indexOf(webVrController);
  86988. if (controllerIndex !== -1) {
  86989. _this.controllers.splice(controllerIndex, 1);
  86990. }
  86991. }
  86992. });
  86993. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  86994. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86995. var webVrController_1 = gamepad;
  86996. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  86997. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  86998. if (_this.webVROptions.controllerMeshes) {
  86999. if (webVrController_1.defaultModel) {
  87000. webVrController_1.defaultModel.setEnabled(true);
  87001. }
  87002. else {
  87003. // Load the meshes
  87004. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  87005. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  87006. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  87007. if (_this.webVROptions.defaultLightingOnControllers) {
  87008. if (!_this._lightOnControllers) {
  87009. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  87010. }
  87011. var activateLightOnSubMeshes_1 = function (mesh, light) {
  87012. var children = mesh.getChildren();
  87013. if (children.length !== 0) {
  87014. children.forEach(function (mesh) {
  87015. light.includedOnlyMeshes.push(mesh);
  87016. activateLightOnSubMeshes_1(mesh, light);
  87017. });
  87018. }
  87019. };
  87020. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  87021. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  87022. }
  87023. });
  87024. }
  87025. }
  87026. webVrController_1.attachToPoseControlledCamera(_this);
  87027. // since this is async - sanity check. Is the controller already stored?
  87028. if (_this.controllers.indexOf(webVrController_1) === -1) {
  87029. //add to the controllers array
  87030. _this.controllers.push(webVrController_1);
  87031. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  87032. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  87033. // So we're overriding setting left & right manually to be sure
  87034. var firstViveWandDetected = false;
  87035. for (var i = 0; i < _this.controllers.length; i++) {
  87036. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87037. if (!firstViveWandDetected) {
  87038. firstViveWandDetected = true;
  87039. _this.controllers[i].hand = "left";
  87040. }
  87041. else {
  87042. _this.controllers[i].hand = "right";
  87043. }
  87044. }
  87045. }
  87046. //did we find enough controllers? Great! let the developer know.
  87047. if (_this.controllers.length >= 2) {
  87048. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  87049. }
  87050. }
  87051. }
  87052. });
  87053. };
  87054. return WebVRFreeCamera;
  87055. }(BABYLON.FreeCamera));
  87056. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  87057. })(BABYLON || (BABYLON = {}));
  87058. //# sourceMappingURL=babylon.webVRCamera.js.map
  87059. var BABYLON;
  87060. (function (BABYLON) {
  87061. // We're mainly based on the logic defined into the FreeCamera code
  87062. /**
  87063. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  87064. * being tilted forward or back and left or right.
  87065. */
  87066. var DeviceOrientationCamera = /** @class */ (function (_super) {
  87067. __extends(DeviceOrientationCamera, _super);
  87068. /**
  87069. * Creates a new device orientation camera
  87070. * @param name The name of the camera
  87071. * @param position The start position camera
  87072. * @param scene The scene the camera belongs to
  87073. */
  87074. function DeviceOrientationCamera(name, position, scene) {
  87075. var _this = _super.call(this, name, position, scene) || this;
  87076. _this._quaternionCache = new BABYLON.Quaternion();
  87077. _this.inputs.addDeviceOrientation();
  87078. return _this;
  87079. }
  87080. /**
  87081. * Gets the current instance class name ("DeviceOrientationCamera").
  87082. * This helps avoiding instanceof at run time.
  87083. * @returns the class name
  87084. */
  87085. DeviceOrientationCamera.prototype.getClassName = function () {
  87086. return "DeviceOrientationCamera";
  87087. };
  87088. /**
  87089. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  87090. */
  87091. DeviceOrientationCamera.prototype._checkInputs = function () {
  87092. _super.prototype._checkInputs.call(this);
  87093. this._quaternionCache.copyFrom(this.rotationQuaternion);
  87094. if (this._initialQuaternion) {
  87095. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87096. }
  87097. };
  87098. /**
  87099. * Reset the camera to its default orientation on the specified axis only.
  87100. * @param axis The axis to reset
  87101. */
  87102. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  87103. var _this = this;
  87104. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  87105. //can only work if this camera has a rotation quaternion already.
  87106. if (!this.rotationQuaternion)
  87107. return;
  87108. if (!this._initialQuaternion) {
  87109. this._initialQuaternion = new BABYLON.Quaternion();
  87110. }
  87111. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  87112. ['x', 'y', 'z'].forEach(function (axisName) {
  87113. if (!axis[axisName]) {
  87114. _this._initialQuaternion[axisName] = 0;
  87115. }
  87116. else {
  87117. _this._initialQuaternion[axisName] *= -1;
  87118. }
  87119. });
  87120. this._initialQuaternion.normalize();
  87121. //force rotation update
  87122. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87123. };
  87124. return DeviceOrientationCamera;
  87125. }(BABYLON.FreeCamera));
  87126. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87127. })(BABYLON || (BABYLON = {}));
  87128. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87129. var BABYLON;
  87130. (function (BABYLON) {
  87131. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87132. __extends(VRDeviceOrientationFreeCamera, _super);
  87133. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87134. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87135. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87136. var _this = _super.call(this, name, position, scene) || this;
  87137. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87138. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87139. return _this;
  87140. }
  87141. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87142. return "VRDeviceOrientationFreeCamera";
  87143. };
  87144. return VRDeviceOrientationFreeCamera;
  87145. }(BABYLON.DeviceOrientationCamera));
  87146. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87147. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87148. __extends(VRDeviceOrientationGamepadCamera, _super);
  87149. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87150. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87151. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87152. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87153. _this.inputs.addGamepad();
  87154. return _this;
  87155. }
  87156. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87157. return "VRDeviceOrientationGamepadCamera";
  87158. };
  87159. return VRDeviceOrientationGamepadCamera;
  87160. }(VRDeviceOrientationFreeCamera));
  87161. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87162. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87163. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87164. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87165. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87166. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87167. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87168. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87169. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87170. _this.inputs.addVRDeviceOrientation();
  87171. return _this;
  87172. }
  87173. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87174. return "VRDeviceOrientationArcRotateCamera";
  87175. };
  87176. return VRDeviceOrientationArcRotateCamera;
  87177. }(BABYLON.ArcRotateCamera));
  87178. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87179. })(BABYLON || (BABYLON = {}));
  87180. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87181. var BABYLON;
  87182. (function (BABYLON) {
  87183. /**
  87184. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87185. */
  87186. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87187. __extends(AnaglyphFreeCamera, _super);
  87188. /**
  87189. * Creates a new AnaglyphFreeCamera
  87190. * @param name defines camera name
  87191. * @param position defines initial position
  87192. * @param interaxialDistance defines distance between each color axis
  87193. * @param scene defines the hosting scene
  87194. */
  87195. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87196. var _this = _super.call(this, name, position, scene) || this;
  87197. _this.interaxialDistance = interaxialDistance;
  87198. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87199. return _this;
  87200. }
  87201. /**
  87202. * Gets camera class name
  87203. * @returns AnaglyphFreeCamera
  87204. */
  87205. AnaglyphFreeCamera.prototype.getClassName = function () {
  87206. return "AnaglyphFreeCamera";
  87207. };
  87208. return AnaglyphFreeCamera;
  87209. }(BABYLON.FreeCamera));
  87210. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87211. /**
  87212. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87213. */
  87214. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87215. __extends(AnaglyphArcRotateCamera, _super);
  87216. /**
  87217. * Creates a new AnaglyphArcRotateCamera
  87218. * @param name defines camera name
  87219. * @param alpha defines alpha angle (in radians)
  87220. * @param beta defines beta angle (in radians)
  87221. * @param radius defines radius
  87222. * @param target defines camera target
  87223. * @param interaxialDistance defines distance between each color axis
  87224. * @param scene defines the hosting scene
  87225. */
  87226. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87227. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87228. _this.interaxialDistance = interaxialDistance;
  87229. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87230. return _this;
  87231. }
  87232. /**
  87233. * Gets camera class name
  87234. * @returns AnaglyphArcRotateCamera
  87235. */
  87236. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87237. return "AnaglyphArcRotateCamera";
  87238. };
  87239. return AnaglyphArcRotateCamera;
  87240. }(BABYLON.ArcRotateCamera));
  87241. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87242. /**
  87243. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87244. */
  87245. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87246. __extends(AnaglyphGamepadCamera, _super);
  87247. /**
  87248. * Creates a new AnaglyphGamepadCamera
  87249. * @param name defines camera name
  87250. * @param position defines initial position
  87251. * @param interaxialDistance defines distance between each color axis
  87252. * @param scene defines the hosting scene
  87253. */
  87254. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87255. var _this = _super.call(this, name, position, scene) || this;
  87256. _this.interaxialDistance = interaxialDistance;
  87257. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87258. return _this;
  87259. }
  87260. /**
  87261. * Gets camera class name
  87262. * @returns AnaglyphGamepadCamera
  87263. */
  87264. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87265. return "AnaglyphGamepadCamera";
  87266. };
  87267. return AnaglyphGamepadCamera;
  87268. }(BABYLON.GamepadCamera));
  87269. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87270. /**
  87271. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87272. */
  87273. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87274. __extends(AnaglyphUniversalCamera, _super);
  87275. /**
  87276. * Creates a new AnaglyphUniversalCamera
  87277. * @param name defines camera name
  87278. * @param position defines initial position
  87279. * @param interaxialDistance defines distance between each color axis
  87280. * @param scene defines the hosting scene
  87281. */
  87282. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87283. var _this = _super.call(this, name, position, scene) || this;
  87284. _this.interaxialDistance = interaxialDistance;
  87285. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87286. return _this;
  87287. }
  87288. /**
  87289. * Gets camera class name
  87290. * @returns AnaglyphUniversalCamera
  87291. */
  87292. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87293. return "AnaglyphUniversalCamera";
  87294. };
  87295. return AnaglyphUniversalCamera;
  87296. }(BABYLON.UniversalCamera));
  87297. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87298. /**
  87299. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87300. */
  87301. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87302. __extends(StereoscopicFreeCamera, _super);
  87303. /**
  87304. * Creates a new StereoscopicFreeCamera
  87305. * @param name defines camera name
  87306. * @param position defines initial position
  87307. * @param interaxialDistance defines distance between each color axis
  87308. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87309. * @param scene defines the hosting scene
  87310. */
  87311. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87312. var _this = _super.call(this, name, position, scene) || this;
  87313. _this.interaxialDistance = interaxialDistance;
  87314. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87315. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87316. return _this;
  87317. }
  87318. /**
  87319. * Gets camera class name
  87320. * @returns StereoscopicFreeCamera
  87321. */
  87322. StereoscopicFreeCamera.prototype.getClassName = function () {
  87323. return "StereoscopicFreeCamera";
  87324. };
  87325. return StereoscopicFreeCamera;
  87326. }(BABYLON.FreeCamera));
  87327. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87328. /**
  87329. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87330. */
  87331. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87332. __extends(StereoscopicArcRotateCamera, _super);
  87333. /**
  87334. * Creates a new StereoscopicArcRotateCamera
  87335. * @param name defines camera name
  87336. * @param alpha defines alpha angle (in radians)
  87337. * @param beta defines beta angle (in radians)
  87338. * @param radius defines radius
  87339. * @param target defines camera target
  87340. * @param interaxialDistance defines distance between each color axis
  87341. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87342. * @param scene defines the hosting scene
  87343. */
  87344. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87345. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87346. _this.interaxialDistance = interaxialDistance;
  87347. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87348. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87349. return _this;
  87350. }
  87351. /**
  87352. * Gets camera class name
  87353. * @returns StereoscopicArcRotateCamera
  87354. */
  87355. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  87356. return "StereoscopicArcRotateCamera";
  87357. };
  87358. return StereoscopicArcRotateCamera;
  87359. }(BABYLON.ArcRotateCamera));
  87360. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  87361. /**
  87362. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  87363. */
  87364. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  87365. __extends(StereoscopicGamepadCamera, _super);
  87366. /**
  87367. * Creates a new StereoscopicGamepadCamera
  87368. * @param name defines camera name
  87369. * @param position defines initial position
  87370. * @param interaxialDistance defines distance between each color axis
  87371. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87372. * @param scene defines the hosting scene
  87373. */
  87374. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87375. var _this = _super.call(this, name, position, scene) || this;
  87376. _this.interaxialDistance = interaxialDistance;
  87377. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87378. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87379. return _this;
  87380. }
  87381. /**
  87382. * Gets camera class name
  87383. * @returns StereoscopicGamepadCamera
  87384. */
  87385. StereoscopicGamepadCamera.prototype.getClassName = function () {
  87386. return "StereoscopicGamepadCamera";
  87387. };
  87388. return StereoscopicGamepadCamera;
  87389. }(BABYLON.GamepadCamera));
  87390. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  87391. /**
  87392. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  87393. */
  87394. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  87395. __extends(StereoscopicUniversalCamera, _super);
  87396. /**
  87397. * Creates a new StereoscopicUniversalCamera
  87398. * @param name defines camera name
  87399. * @param position defines initial position
  87400. * @param interaxialDistance defines distance between each color axis
  87401. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87402. * @param scene defines the hosting scene
  87403. */
  87404. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87405. var _this = _super.call(this, name, position, scene) || this;
  87406. _this.interaxialDistance = interaxialDistance;
  87407. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87408. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87409. return _this;
  87410. }
  87411. /**
  87412. * Gets camera class name
  87413. * @returns StereoscopicUniversalCamera
  87414. */
  87415. StereoscopicUniversalCamera.prototype.getClassName = function () {
  87416. return "StereoscopicUniversalCamera";
  87417. };
  87418. return StereoscopicUniversalCamera;
  87419. }(BABYLON.UniversalCamera));
  87420. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  87421. })(BABYLON || (BABYLON = {}));
  87422. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  87423. var BABYLON;
  87424. (function (BABYLON) {
  87425. var VRExperienceHelperGazer = /** @class */ (function () {
  87426. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  87427. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  87428. this.scene = scene;
  87429. this._pointerDownOnMeshAsked = false;
  87430. this._isActionableMesh = false;
  87431. this._teleportationRequestInitiated = false;
  87432. this._teleportationBackRequestInitiated = false;
  87433. this._rotationRightAsked = false;
  87434. this._rotationLeftAsked = false;
  87435. this._dpadPressed = true;
  87436. this._activePointer = false;
  87437. this._id = VRExperienceHelperGazer._idCounter++;
  87438. // Gaze tracker
  87439. if (!gazeTrackerToClone) {
  87440. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  87441. this._gazeTracker.bakeCurrentTransformIntoVertices();
  87442. this._gazeTracker.isPickable = false;
  87443. this._gazeTracker.isVisible = false;
  87444. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  87445. targetMat.specularColor = BABYLON.Color3.Black();
  87446. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87447. targetMat.backFaceCulling = false;
  87448. this._gazeTracker.material = targetMat;
  87449. }
  87450. else {
  87451. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  87452. }
  87453. }
  87454. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  87455. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  87456. };
  87457. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  87458. this._pointerDownOnMeshAsked = true;
  87459. if (this._currentMeshSelected && this._currentHit) {
  87460. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  87461. }
  87462. };
  87463. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  87464. if (this._currentMeshSelected && this._currentHit) {
  87465. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  87466. }
  87467. this._pointerDownOnMeshAsked = false;
  87468. };
  87469. VRExperienceHelperGazer.prototype._activatePointer = function () {
  87470. this._activePointer = true;
  87471. };
  87472. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  87473. this._activePointer = false;
  87474. };
  87475. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  87476. if (distance === void 0) { distance = 100; }
  87477. };
  87478. VRExperienceHelperGazer.prototype.dispose = function () {
  87479. this._interactionsEnabled = false;
  87480. this._teleportationEnabled = false;
  87481. if (this._gazeTracker) {
  87482. this._gazeTracker.dispose();
  87483. }
  87484. };
  87485. VRExperienceHelperGazer._idCounter = 0;
  87486. return VRExperienceHelperGazer;
  87487. }());
  87488. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  87489. __extends(VRExperienceHelperControllerGazer, _super);
  87490. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  87491. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  87492. _this.webVRController = webVRController;
  87493. // Laser pointer
  87494. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  87495. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  87496. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87497. laserPointerMaterial.alpha = 0.6;
  87498. _this._laserPointer.material = laserPointerMaterial;
  87499. _this._laserPointer.rotation.x = Math.PI / 2;
  87500. _this._laserPointer.position.z = -0.5;
  87501. _this._laserPointer.isVisible = false;
  87502. if (!webVRController.mesh) {
  87503. // Create an empty mesh that is used prior to loading the high quality model
  87504. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  87505. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  87506. preloadPointerPose.rotation.x = -0.7;
  87507. preloadMesh.addChild(preloadPointerPose);
  87508. webVRController.attachToMesh(preloadMesh);
  87509. }
  87510. _this._setLaserPointerParent(webVRController.mesh);
  87511. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  87512. _this._setLaserPointerParent(mesh);
  87513. });
  87514. return _this;
  87515. }
  87516. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  87517. return this.webVRController.getForwardRay(length);
  87518. };
  87519. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  87520. _super.prototype._activatePointer.call(this);
  87521. this._laserPointer.isVisible = true;
  87522. };
  87523. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  87524. _super.prototype._deactivatePointer.call(this);
  87525. this._laserPointer.isVisible = false;
  87526. };
  87527. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  87528. this._laserPointer.material.emissiveColor = color;
  87529. };
  87530. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  87531. var makeNotPick = function (root) {
  87532. root.name += " laserPointer";
  87533. root.getChildMeshes().forEach(function (c) {
  87534. makeNotPick(c);
  87535. });
  87536. };
  87537. makeNotPick(mesh);
  87538. var childMeshes = mesh.getChildMeshes();
  87539. this.webVRController._pointingPoseNode = null;
  87540. for (var i = 0; i < childMeshes.length; i++) {
  87541. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  87542. mesh = childMeshes[i];
  87543. this.webVRController._pointingPoseNode = mesh;
  87544. break;
  87545. }
  87546. }
  87547. this._laserPointer.parent = mesh;
  87548. };
  87549. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  87550. if (distance === void 0) { distance = 100; }
  87551. this._laserPointer.scaling.y = distance;
  87552. this._laserPointer.position.z = -distance / 2;
  87553. };
  87554. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  87555. _super.prototype.dispose.call(this);
  87556. this._laserPointer.dispose();
  87557. if (this._meshAttachedObserver) {
  87558. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  87559. }
  87560. };
  87561. return VRExperienceHelperControllerGazer;
  87562. }(VRExperienceHelperGazer));
  87563. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  87564. __extends(VRExperienceHelperCameraGazer, _super);
  87565. function VRExperienceHelperCameraGazer(getCamera, scene) {
  87566. var _this = _super.call(this, scene) || this;
  87567. _this.getCamera = getCamera;
  87568. return _this;
  87569. }
  87570. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  87571. var camera = this.getCamera();
  87572. if (camera) {
  87573. return camera.getForwardRay(length);
  87574. }
  87575. else {
  87576. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  87577. }
  87578. };
  87579. return VRExperienceHelperCameraGazer;
  87580. }(VRExperienceHelperGazer));
  87581. /**
  87582. * Helps to quickly add VR support to an existing scene.
  87583. * See http://doc.babylonjs.com/how_to/webvr_helper
  87584. */
  87585. var VRExperienceHelper = /** @class */ (function () {
  87586. /**
  87587. * Instantiates a VRExperienceHelper.
  87588. * Helps to quickly add VR support to an existing scene.
  87589. * @param scene The scene the VRExperienceHelper belongs to.
  87590. * @param webVROptions Options to modify the vr experience helper's behavior.
  87591. */
  87592. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  87593. if (webVROptions === void 0) { webVROptions = {}; }
  87594. var _this = this;
  87595. this.webVROptions = webVROptions;
  87596. // Can the system support WebVR, even if a headset isn't plugged in?
  87597. this._webVRsupported = false;
  87598. // If WebVR is supported, is a headset plugged in and are we ready to present?
  87599. this._webVRready = false;
  87600. // Are we waiting for the requestPresent callback to complete?
  87601. this._webVRrequesting = false;
  87602. // Are we presenting to the headset right now?
  87603. this._webVRpresenting = false;
  87604. // Are we presenting in the fullscreen fallback?
  87605. this._fullscreenVRpresenting = false;
  87606. /**
  87607. * Observable raised when entering VR.
  87608. */
  87609. this.onEnteringVRObservable = new BABYLON.Observable();
  87610. /**
  87611. * Observable raised when exiting VR.
  87612. */
  87613. this.onExitingVRObservable = new BABYLON.Observable();
  87614. /**
  87615. * Observable raised when controller mesh is loaded.
  87616. */
  87617. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87618. this._useCustomVRButton = false;
  87619. this._teleportationRequested = false;
  87620. this._teleportActive = false;
  87621. this._floorMeshesCollection = [];
  87622. this._rotationAllowed = true;
  87623. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  87624. this._isDefaultTeleportationTarget = true;
  87625. this._teleportationFillColor = "#444444";
  87626. this._teleportationBorderColor = "#FFFFFF";
  87627. this._rotationAngle = 0;
  87628. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  87629. this._padSensibilityUp = 0.65;
  87630. this._padSensibilityDown = 0.35;
  87631. this.leftController = null;
  87632. this.rightController = null;
  87633. /**
  87634. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  87635. */
  87636. this.onNewMeshSelected = new BABYLON.Observable();
  87637. /**
  87638. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  87639. */
  87640. this.onNewMeshPicked = new BABYLON.Observable();
  87641. /**
  87642. * Observable raised before camera teleportation
  87643. */
  87644. this.onBeforeCameraTeleport = new BABYLON.Observable();
  87645. /**
  87646. * Observable raised after camera teleportation
  87647. */
  87648. this.onAfterCameraTeleport = new BABYLON.Observable();
  87649. /**
  87650. * Observable raised when current selected mesh gets unselected
  87651. */
  87652. this.onSelectedMeshUnselected = new BABYLON.Observable();
  87653. /**
  87654. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  87655. */
  87656. this.teleportationEnabled = true;
  87657. this._teleportationInitialized = false;
  87658. this._interactionsEnabled = false;
  87659. this._interactionsRequested = false;
  87660. this._displayGaze = true;
  87661. this._displayLaserPointer = true;
  87662. this._onResize = function () {
  87663. _this.moveButtonToBottomRight();
  87664. if (_this._fullscreenVRpresenting && _this._webVRready) {
  87665. _this.exitVR();
  87666. }
  87667. };
  87668. this._onFullscreenChange = function () {
  87669. if (document.fullscreen !== undefined) {
  87670. _this._fullscreenVRpresenting = document.fullscreen;
  87671. }
  87672. else if (document.mozFullScreen !== undefined) {
  87673. _this._fullscreenVRpresenting = document.mozFullScreen;
  87674. }
  87675. else if (document.webkitIsFullScreen !== undefined) {
  87676. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  87677. }
  87678. else if (document.msIsFullScreen !== undefined) {
  87679. _this._fullscreenVRpresenting = document.msIsFullScreen;
  87680. }
  87681. if (!_this._fullscreenVRpresenting && _this._canvas) {
  87682. _this.exitVR();
  87683. if (!_this._useCustomVRButton) {
  87684. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  87685. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  87686. }
  87687. }
  87688. };
  87689. this.beforeRender = function () {
  87690. if (_this.leftController && _this.leftController._activePointer) {
  87691. _this._castRayAndSelectObject(_this.leftController);
  87692. }
  87693. if (_this.rightController && _this.rightController._activePointer) {
  87694. _this._castRayAndSelectObject(_this.rightController);
  87695. }
  87696. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  87697. _this._castRayAndSelectObject(_this._cameraGazer);
  87698. }
  87699. else {
  87700. _this._cameraGazer._gazeTracker.isVisible = false;
  87701. }
  87702. };
  87703. this._onNewGamepadConnected = function (gamepad) {
  87704. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  87705. if (gamepad.leftStick) {
  87706. gamepad.onleftstickchanged(function (stickValues) {
  87707. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  87708. // Listening to classic/xbox gamepad only if no VR controller is active
  87709. if ((!_this.leftController && !_this.rightController) ||
  87710. ((_this.leftController && !_this.leftController._activePointer) &&
  87711. (_this.rightController && !_this.rightController._activePointer))) {
  87712. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  87713. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  87714. }
  87715. }
  87716. });
  87717. }
  87718. if (gamepad.rightStick) {
  87719. gamepad.onrightstickchanged(function (stickValues) {
  87720. if (_this._teleportationInitialized) {
  87721. _this._checkRotate(stickValues, _this._cameraGazer);
  87722. }
  87723. });
  87724. }
  87725. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  87726. gamepad.onbuttondown(function (buttonPressed) {
  87727. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87728. _this._cameraGazer._selectionPointerDown();
  87729. }
  87730. });
  87731. gamepad.onbuttonup(function (buttonPressed) {
  87732. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87733. _this._cameraGazer._selectionPointerUp();
  87734. }
  87735. });
  87736. }
  87737. }
  87738. else {
  87739. var webVRController = gamepad;
  87740. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  87741. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  87742. _this.rightController = controller;
  87743. }
  87744. else {
  87745. _this.leftController = controller;
  87746. }
  87747. _this._tryEnableInteractionOnController(controller);
  87748. }
  87749. };
  87750. // 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
  87751. this._tryEnableInteractionOnController = function (controller) {
  87752. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87753. _this._enableInteractionOnController(controller);
  87754. }
  87755. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87756. _this._enableTeleportationOnController(controller);
  87757. }
  87758. };
  87759. this._onNewGamepadDisconnected = function (gamepad) {
  87760. if (gamepad instanceof BABYLON.WebVRController) {
  87761. if (gamepad.hand === "left" && _this.leftController != null) {
  87762. _this.leftController.dispose();
  87763. _this.leftController = null;
  87764. }
  87765. if (gamepad.hand === "right" && _this.rightController != null) {
  87766. _this.rightController.dispose();
  87767. _this.rightController = null;
  87768. }
  87769. }
  87770. };
  87771. this._workingVector = BABYLON.Vector3.Zero();
  87772. this._workingQuaternion = BABYLON.Quaternion.Identity();
  87773. this._workingMatrix = BABYLON.Matrix.Identity();
  87774. this._scene = scene;
  87775. this._canvas = scene.getEngine().getRenderingCanvas();
  87776. // Parse options
  87777. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  87778. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  87779. }
  87780. if (webVROptions.createDeviceOrientationCamera === undefined) {
  87781. webVROptions.createDeviceOrientationCamera = true;
  87782. }
  87783. if (webVROptions.defaultHeight === undefined) {
  87784. webVROptions.defaultHeight = 1.7;
  87785. }
  87786. if (webVROptions.useCustomVRButton) {
  87787. this._useCustomVRButton = true;
  87788. if (webVROptions.customVRButton) {
  87789. this._btnVR = webVROptions.customVRButton;
  87790. }
  87791. }
  87792. if (webVROptions.rayLength) {
  87793. this._rayLength = webVROptions.rayLength;
  87794. }
  87795. this._defaultHeight = webVROptions.defaultHeight;
  87796. if (webVROptions.positionScale) {
  87797. this._rayLength *= webVROptions.positionScale;
  87798. this._defaultHeight *= webVROptions.positionScale;
  87799. }
  87800. // Set position
  87801. if (this._scene.activeCamera) {
  87802. this._position = this._scene.activeCamera.position.clone();
  87803. }
  87804. else {
  87805. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  87806. }
  87807. // Set non-vr camera
  87808. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  87809. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  87810. // Copy data from existing camera
  87811. if (this._scene.activeCamera) {
  87812. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87813. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  87814. // Set rotation from previous camera
  87815. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  87816. var targetCamera = this._scene.activeCamera;
  87817. if (targetCamera.rotationQuaternion) {
  87818. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  87819. }
  87820. else {
  87821. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  87822. }
  87823. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  87824. }
  87825. }
  87826. this._scene.activeCamera = this._deviceOrientationCamera;
  87827. if (this._canvas) {
  87828. this._scene.activeCamera.attachControl(this._canvas);
  87829. }
  87830. }
  87831. else {
  87832. this._existingCamera = this._scene.activeCamera;
  87833. }
  87834. // Create VR cameras
  87835. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87836. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  87837. }
  87838. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  87839. this._webVRCamera.useStandingMatrix();
  87840. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  87841. // Create default button
  87842. if (!this._useCustomVRButton) {
  87843. this._btnVR = document.createElement("BUTTON");
  87844. this._btnVR.className = "babylonVRicon";
  87845. this._btnVR.id = "babylonVRiconbtn";
  87846. this._btnVR.title = "Click to switch to VR";
  87847. 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) }";
  87848. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  87849. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  87850. // css += ".babylonVRicon.vrdisplaysupported { }";
  87851. // css += ".babylonVRicon.vrdisplayready { }";
  87852. // css += ".babylonVRicon.vrdisplayrequesting { }";
  87853. var style = document.createElement('style');
  87854. style.appendChild(document.createTextNode(css));
  87855. document.getElementsByTagName('head')[0].appendChild(style);
  87856. this.moveButtonToBottomRight();
  87857. }
  87858. // VR button click event
  87859. if (this._btnVR) {
  87860. this._btnVR.addEventListener("click", function () {
  87861. if (!_this.isInVRMode) {
  87862. _this.enterVR();
  87863. }
  87864. else {
  87865. _this.exitVR();
  87866. }
  87867. });
  87868. }
  87869. // Window events
  87870. window.addEventListener("resize", this._onResize);
  87871. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  87872. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  87873. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  87874. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  87875. // Display vr button when headset is connected
  87876. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87877. this.displayVRButton();
  87878. }
  87879. else {
  87880. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  87881. if (e.vrDisplay) {
  87882. _this.displayVRButton();
  87883. }
  87884. });
  87885. }
  87886. // Exiting VR mode using 'ESC' key on desktop
  87887. this._onKeyDown = function (event) {
  87888. if (event.keyCode === 27 && _this.isInVRMode) {
  87889. _this.exitVR();
  87890. }
  87891. };
  87892. document.addEventListener("keydown", this._onKeyDown);
  87893. // Exiting VR mode double tapping the touch screen
  87894. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  87895. if (_this.isInVRMode) {
  87896. _this.exitVR();
  87897. if (_this._fullscreenVRpresenting) {
  87898. _this._scene.getEngine().switchFullscreen(true);
  87899. }
  87900. }
  87901. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  87902. // Listen for WebVR display changes
  87903. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  87904. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  87905. this._onVRRequestPresentStart = function () {
  87906. _this._webVRrequesting = true;
  87907. _this.updateButtonVisibility();
  87908. };
  87909. this._onVRRequestPresentComplete = function (success) {
  87910. _this._webVRrequesting = false;
  87911. _this.updateButtonVisibility();
  87912. };
  87913. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  87914. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  87915. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  87916. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87917. scene.onDisposeObservable.add(function () {
  87918. _this.dispose();
  87919. });
  87920. // Gamepad connection events
  87921. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  87922. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  87923. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  87924. this.updateButtonVisibility();
  87925. //create easing functions
  87926. this._circleEase = new BABYLON.CircleEase();
  87927. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87928. }
  87929. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  87930. /** Return this.onEnteringVRObservable
  87931. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  87932. */
  87933. get: function () {
  87934. return this.onEnteringVRObservable;
  87935. },
  87936. enumerable: true,
  87937. configurable: true
  87938. });
  87939. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  87940. /** Return this.onExitingVRObservable
  87941. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  87942. */
  87943. get: function () {
  87944. return this.onExitingVRObservable;
  87945. },
  87946. enumerable: true,
  87947. configurable: true
  87948. });
  87949. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  87950. /** Return this.onControllerMeshLoadedObservable
  87951. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  87952. */
  87953. get: function () {
  87954. return this.onControllerMeshLoadedObservable;
  87955. },
  87956. enumerable: true,
  87957. configurable: true
  87958. });
  87959. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  87960. /**
  87961. * The mesh used to display where the user is going to teleport.
  87962. */
  87963. get: function () {
  87964. return this._teleportationTarget;
  87965. },
  87966. /**
  87967. * Sets the mesh to be used to display where the user is going to teleport.
  87968. */
  87969. set: function (value) {
  87970. if (value) {
  87971. value.name = "teleportationTarget";
  87972. this._isDefaultTeleportationTarget = false;
  87973. this._teleportationTarget = value;
  87974. }
  87975. },
  87976. enumerable: true,
  87977. configurable: true
  87978. });
  87979. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  87980. /**
  87981. * The mesh used to display where the user is selecting,
  87982. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  87983. * See http://doc.babylonjs.com/resources/baking_transformations
  87984. */
  87985. get: function () {
  87986. return this._cameraGazer._gazeTracker;
  87987. },
  87988. set: function (value) {
  87989. if (value) {
  87990. this._cameraGazer._gazeTracker = value;
  87991. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  87992. this._cameraGazer._gazeTracker.isPickable = false;
  87993. this._cameraGazer._gazeTracker.isVisible = false;
  87994. this._cameraGazer._gazeTracker.name = "gazeTracker";
  87995. if (this.leftController) {
  87996. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87997. }
  87998. if (this.rightController) {
  87999. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88000. }
  88001. }
  88002. },
  88003. enumerable: true,
  88004. configurable: true
  88005. });
  88006. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  88007. /**
  88008. * If the ray of the gaze should be displayed.
  88009. */
  88010. get: function () {
  88011. return this._displayGaze;
  88012. },
  88013. /**
  88014. * Sets if the ray of the gaze should be displayed.
  88015. */
  88016. set: function (value) {
  88017. this._displayGaze = value;
  88018. if (!value) {
  88019. this._cameraGazer._gazeTracker.isVisible = false;
  88020. if (this.leftController) {
  88021. this.leftController._gazeTracker.isVisible = false;
  88022. }
  88023. if (this.rightController) {
  88024. this.rightController._gazeTracker.isVisible = false;
  88025. }
  88026. }
  88027. },
  88028. enumerable: true,
  88029. configurable: true
  88030. });
  88031. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  88032. /**
  88033. * If the ray of the LaserPointer should be displayed.
  88034. */
  88035. get: function () {
  88036. return this._displayLaserPointer;
  88037. },
  88038. /**
  88039. * Sets if the ray of the LaserPointer should be displayed.
  88040. */
  88041. set: function (value) {
  88042. this._displayLaserPointer = value;
  88043. if (!value) {
  88044. if (this.rightController) {
  88045. this.rightController._deactivatePointer();
  88046. this.rightController._gazeTracker.isVisible = false;
  88047. }
  88048. if (this.leftController) {
  88049. this.leftController._deactivatePointer();
  88050. this.leftController._gazeTracker.isVisible = false;
  88051. }
  88052. }
  88053. else {
  88054. if (this.rightController) {
  88055. this.rightController._activatePointer();
  88056. }
  88057. if (this.leftController) {
  88058. this.leftController._activatePointer();
  88059. }
  88060. }
  88061. },
  88062. enumerable: true,
  88063. configurable: true
  88064. });
  88065. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  88066. /**
  88067. * The deviceOrientationCamera used as the camera when not in VR.
  88068. */
  88069. get: function () {
  88070. return this._deviceOrientationCamera;
  88071. },
  88072. enumerable: true,
  88073. configurable: true
  88074. });
  88075. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  88076. /**
  88077. * Based on the current WebVR support, returns the current VR camera used.
  88078. */
  88079. get: function () {
  88080. if (this._webVRready) {
  88081. return this._webVRCamera;
  88082. }
  88083. else {
  88084. return this._scene.activeCamera;
  88085. }
  88086. },
  88087. enumerable: true,
  88088. configurable: true
  88089. });
  88090. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  88091. /**
  88092. * The webVRCamera which is used when in VR.
  88093. */
  88094. get: function () {
  88095. return this._webVRCamera;
  88096. },
  88097. enumerable: true,
  88098. configurable: true
  88099. });
  88100. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  88101. /**
  88102. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  88103. */
  88104. get: function () {
  88105. return this._vrDeviceOrientationCamera;
  88106. },
  88107. enumerable: true,
  88108. configurable: true
  88109. });
  88110. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  88111. get: function () {
  88112. var result = this._cameraGazer._teleportationRequestInitiated
  88113. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  88114. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  88115. return result;
  88116. },
  88117. enumerable: true,
  88118. configurable: true
  88119. });
  88120. // Raised when one of the controller has loaded successfully its associated default mesh
  88121. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  88122. if (this.leftController && this.leftController.webVRController == webVRController) {
  88123. if (webVRController.mesh) {
  88124. this.leftController._setLaserPointerParent(webVRController.mesh);
  88125. }
  88126. }
  88127. if (this.rightController && this.rightController.webVRController == webVRController) {
  88128. if (webVRController.mesh) {
  88129. this.rightController._setLaserPointerParent(webVRController.mesh);
  88130. }
  88131. }
  88132. try {
  88133. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88134. }
  88135. catch (err) {
  88136. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88137. }
  88138. };
  88139. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88140. /**
  88141. * Gets a value indicating if we are currently in VR mode.
  88142. */
  88143. get: function () {
  88144. return this._webVRpresenting || this._fullscreenVRpresenting;
  88145. },
  88146. enumerable: true,
  88147. configurable: true
  88148. });
  88149. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88150. var vrDisplay = this._scene.getEngine().getVRDevice();
  88151. if (vrDisplay) {
  88152. var wasPresenting = this._webVRpresenting;
  88153. // A VR display is connected
  88154. this._webVRpresenting = vrDisplay.isPresenting;
  88155. if (wasPresenting && !this._webVRpresenting)
  88156. this.exitVR();
  88157. }
  88158. else {
  88159. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88160. }
  88161. this.updateButtonVisibility();
  88162. };
  88163. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88164. this._webVRsupported = eventArgs.vrSupported;
  88165. this._webVRready = !!eventArgs.vrDisplay;
  88166. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88167. this.updateButtonVisibility();
  88168. };
  88169. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88170. if (this._canvas && !this._useCustomVRButton) {
  88171. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  88172. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  88173. }
  88174. };
  88175. VRExperienceHelper.prototype.displayVRButton = function () {
  88176. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  88177. document.body.appendChild(this._btnVR);
  88178. this._btnVRDisplayed = true;
  88179. }
  88180. };
  88181. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88182. if (!this._btnVR || this._useCustomVRButton) {
  88183. return;
  88184. }
  88185. this._btnVR.className = "babylonVRicon";
  88186. if (this.isInVRMode) {
  88187. this._btnVR.className += " vrdisplaypresenting";
  88188. }
  88189. else {
  88190. if (this._webVRready)
  88191. this._btnVR.className += " vrdisplayready";
  88192. if (this._webVRsupported)
  88193. this._btnVR.className += " vrdisplaysupported";
  88194. if (this._webVRrequesting)
  88195. this._btnVR.className += " vrdisplayrequesting";
  88196. }
  88197. };
  88198. /**
  88199. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88200. * Otherwise, will use the fullscreen API.
  88201. */
  88202. VRExperienceHelper.prototype.enterVR = function () {
  88203. if (this.onEnteringVRObservable) {
  88204. try {
  88205. this.onEnteringVRObservable.notifyObservers(this);
  88206. }
  88207. catch (err) {
  88208. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88209. }
  88210. }
  88211. if (this._scene.activeCamera) {
  88212. this._position = this._scene.activeCamera.position.clone();
  88213. // make sure that we return to the last active camera
  88214. this._existingCamera = this._scene.activeCamera;
  88215. }
  88216. if (this._webVRrequesting)
  88217. return;
  88218. // If WebVR is supported and a headset is connected
  88219. if (this._webVRready) {
  88220. if (!this._webVRpresenting) {
  88221. this._webVRCamera.position = this._position;
  88222. this._scene.activeCamera = this._webVRCamera;
  88223. }
  88224. }
  88225. else if (this._vrDeviceOrientationCamera) {
  88226. this._vrDeviceOrientationCamera.position = this._position;
  88227. if (this._scene.activeCamera) {
  88228. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88229. }
  88230. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88231. this._scene.getEngine().switchFullscreen(true);
  88232. this.updateButtonVisibility();
  88233. }
  88234. if (this._scene.activeCamera && this._canvas) {
  88235. this._scene.activeCamera.attachControl(this._canvas);
  88236. }
  88237. if (this._interactionsEnabled) {
  88238. this._scene.registerBeforeRender(this.beforeRender);
  88239. }
  88240. };
  88241. /**
  88242. * Attempt to exit VR, or fullscreen.
  88243. */
  88244. VRExperienceHelper.prototype.exitVR = function () {
  88245. if (this.onExitingVRObservable) {
  88246. try {
  88247. this.onExitingVRObservable.notifyObservers(this);
  88248. }
  88249. catch (err) {
  88250. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88251. }
  88252. }
  88253. if (this._webVRpresenting) {
  88254. this._scene.getEngine().disableVR();
  88255. }
  88256. if (this._scene.activeCamera) {
  88257. this._position = this._scene.activeCamera.position.clone();
  88258. }
  88259. if (this._deviceOrientationCamera) {
  88260. this._deviceOrientationCamera.position = this._position;
  88261. this._scene.activeCamera = this._deviceOrientationCamera;
  88262. if (this._canvas) {
  88263. this._scene.activeCamera.attachControl(this._canvas);
  88264. }
  88265. }
  88266. else if (this._existingCamera) {
  88267. this._existingCamera.position = this._position;
  88268. this._scene.activeCamera = this._existingCamera;
  88269. }
  88270. this.updateButtonVisibility();
  88271. if (this._interactionsEnabled) {
  88272. this._scene.unregisterBeforeRender(this.beforeRender);
  88273. }
  88274. // resize to update width and height when exiting vr exits fullscreen
  88275. this._scene.getEngine().resize();
  88276. };
  88277. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88278. /**
  88279. * The position of the vr experience helper.
  88280. */
  88281. get: function () {
  88282. return this._position;
  88283. },
  88284. /**
  88285. * Sets the position of the vr experience helper.
  88286. */
  88287. set: function (value) {
  88288. this._position = value;
  88289. if (this._scene.activeCamera) {
  88290. this._scene.activeCamera.position = value;
  88291. }
  88292. },
  88293. enumerable: true,
  88294. configurable: true
  88295. });
  88296. /**
  88297. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88298. */
  88299. VRExperienceHelper.prototype.enableInteractions = function () {
  88300. var _this = this;
  88301. if (!this._interactionsEnabled) {
  88302. this._interactionsRequested = true;
  88303. if (this.leftController) {
  88304. this._enableInteractionOnController(this.leftController);
  88305. }
  88306. if (this.rightController) {
  88307. this._enableInteractionOnController(this.rightController);
  88308. }
  88309. this.raySelectionPredicate = function (mesh) {
  88310. return mesh.isVisible;
  88311. };
  88312. this.meshSelectionPredicate = function (mesh) {
  88313. return true;
  88314. };
  88315. this._raySelectionPredicate = function (mesh) {
  88316. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88317. && mesh.name.indexOf("teleportationTarget") === -1
  88318. && mesh.name.indexOf("torusTeleportation") === -1
  88319. && mesh.name.indexOf("laserPointer") === -1)) {
  88320. return _this.raySelectionPredicate(mesh);
  88321. }
  88322. return false;
  88323. };
  88324. this._interactionsEnabled = true;
  88325. }
  88326. };
  88327. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88328. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88329. if (this._floorMeshesCollection[i].id === mesh.id) {
  88330. return true;
  88331. }
  88332. }
  88333. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88334. return true;
  88335. }
  88336. return false;
  88337. };
  88338. /**
  88339. * Adds a floor mesh to be used for teleportation.
  88340. * @param floorMesh the mesh to be used for teleportation.
  88341. */
  88342. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  88343. if (!this._floorMeshesCollection) {
  88344. return;
  88345. }
  88346. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  88347. return;
  88348. }
  88349. this._floorMeshesCollection.push(floorMesh);
  88350. };
  88351. /**
  88352. * Removes a floor mesh from being used for teleportation.
  88353. * @param floorMesh the mesh to be removed.
  88354. */
  88355. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  88356. if (!this._floorMeshesCollection) {
  88357. return;
  88358. }
  88359. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  88360. if (meshIndex !== -1) {
  88361. this._floorMeshesCollection.splice(meshIndex, 1);
  88362. }
  88363. };
  88364. /**
  88365. * Enables interactions and teleportation using the VR controllers and gaze.
  88366. * @param vrTeleportationOptions options to modify teleportation behavior.
  88367. */
  88368. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  88369. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  88370. if (!this._teleportationInitialized) {
  88371. this._teleportationRequested = true;
  88372. this.enableInteractions();
  88373. if (vrTeleportationOptions.floorMeshName) {
  88374. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  88375. }
  88376. if (vrTeleportationOptions.floorMeshes) {
  88377. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  88378. }
  88379. if (this.leftController != null) {
  88380. this._enableTeleportationOnController(this.leftController);
  88381. }
  88382. if (this.rightController != null) {
  88383. this._enableTeleportationOnController(this.rightController);
  88384. }
  88385. // Creates an image processing post process for the vignette not relying
  88386. // on the main scene configuration for image processing to reduce setup and spaces
  88387. // (gamma/linear) conflicts.
  88388. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  88389. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88390. imageProcessingConfiguration.vignetteEnabled = true;
  88391. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  88392. this._webVRCamera.detachPostProcess(this._postProcessMove);
  88393. this._teleportationInitialized = true;
  88394. if (this._isDefaultTeleportationTarget) {
  88395. this._createTeleportationCircles();
  88396. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  88397. }
  88398. }
  88399. };
  88400. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  88401. var _this = this;
  88402. var controllerMesh = controller.webVRController.mesh;
  88403. if (controllerMesh) {
  88404. controller._interactionsEnabled = true;
  88405. controller._activatePointer();
  88406. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  88407. // Enabling / disabling laserPointer
  88408. if (_this._displayLaserPointer && stateObject.value === 1) {
  88409. if (controller._activePointer) {
  88410. controller._deactivatePointer();
  88411. }
  88412. else {
  88413. controller._activatePointer();
  88414. }
  88415. if (_this.displayGaze) {
  88416. controller._gazeTracker.isVisible = controller._activePointer;
  88417. }
  88418. }
  88419. });
  88420. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  88421. if (!controller._pointerDownOnMeshAsked) {
  88422. if (stateObject.value > _this._padSensibilityUp) {
  88423. controller._selectionPointerDown();
  88424. }
  88425. }
  88426. else if (stateObject.value < _this._padSensibilityDown) {
  88427. controller._selectionPointerUp();
  88428. }
  88429. });
  88430. }
  88431. };
  88432. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  88433. // Dont teleport if another gaze already requested teleportation
  88434. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  88435. return;
  88436. }
  88437. if (!gazer._teleportationRequestInitiated) {
  88438. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  88439. gazer._activatePointer();
  88440. gazer._teleportationRequestInitiated = true;
  88441. }
  88442. }
  88443. else {
  88444. // Listening to the proper controller values changes to confirm teleportation
  88445. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  88446. if (this._teleportActive) {
  88447. this._teleportCamera(this._haloCenter);
  88448. }
  88449. gazer._teleportationRequestInitiated = false;
  88450. }
  88451. }
  88452. };
  88453. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  88454. // Only rotate when user is not currently selecting a teleportation location
  88455. if (gazer._teleportationRequestInitiated) {
  88456. return;
  88457. }
  88458. if (!gazer._rotationLeftAsked) {
  88459. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  88460. gazer._rotationLeftAsked = true;
  88461. if (this._rotationAllowed) {
  88462. this._rotateCamera(false);
  88463. }
  88464. }
  88465. }
  88466. else {
  88467. if (stateObject.x > -this._padSensibilityDown) {
  88468. gazer._rotationLeftAsked = false;
  88469. }
  88470. }
  88471. if (!gazer._rotationRightAsked) {
  88472. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  88473. gazer._rotationRightAsked = true;
  88474. if (this._rotationAllowed) {
  88475. this._rotateCamera(true);
  88476. }
  88477. }
  88478. }
  88479. else {
  88480. if (stateObject.x < this._padSensibilityDown) {
  88481. gazer._rotationRightAsked = false;
  88482. }
  88483. }
  88484. };
  88485. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  88486. // Only teleport backwards when user is not currently selecting a teleportation location
  88487. if (gazer._teleportationRequestInitiated) {
  88488. return;
  88489. }
  88490. // Teleport backwards
  88491. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  88492. if (!gazer._teleportationBackRequestInitiated) {
  88493. if (!this.currentVRCamera) {
  88494. return;
  88495. }
  88496. // Get rotation and position of the current camera
  88497. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  88498. var position = this.currentVRCamera.position;
  88499. // If the camera has device position, use that instead
  88500. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  88501. rotation = this.currentVRCamera.deviceRotationQuaternion;
  88502. position = this.currentVRCamera.devicePosition;
  88503. }
  88504. // Get matrix with only the y rotation of the device rotation
  88505. rotation.toEulerAnglesToRef(this._workingVector);
  88506. this._workingVector.z = 0;
  88507. this._workingVector.x = 0;
  88508. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  88509. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  88510. // Rotate backwards ray by device rotation to cast at the ground behind the user
  88511. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  88512. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  88513. var ray = new BABYLON.Ray(position, this._workingVector);
  88514. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88515. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  88516. this._teleportCamera(hit.pickedPoint);
  88517. }
  88518. gazer._teleportationBackRequestInitiated = true;
  88519. }
  88520. }
  88521. else {
  88522. gazer._teleportationBackRequestInitiated = false;
  88523. }
  88524. };
  88525. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  88526. var _this = this;
  88527. var controllerMesh = controller.webVRController.mesh;
  88528. if (controllerMesh) {
  88529. if (!controller._interactionsEnabled) {
  88530. this._enableInteractionOnController(controller);
  88531. }
  88532. controller._interactionsEnabled = true;
  88533. controller._teleportationEnabled = true;
  88534. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88535. controller._dpadPressed = false;
  88536. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  88537. controller._dpadPressed = stateObject.pressed;
  88538. if (!controller._dpadPressed) {
  88539. controller._rotationLeftAsked = false;
  88540. controller._rotationRightAsked = false;
  88541. controller._teleportationBackRequestInitiated = false;
  88542. }
  88543. });
  88544. }
  88545. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  88546. if (_this.teleportationEnabled) {
  88547. _this._checkTeleportBackwards(stateObject, controller);
  88548. _this._checkTeleportWithRay(stateObject, controller);
  88549. }
  88550. _this._checkRotate(stateObject, controller);
  88551. });
  88552. }
  88553. };
  88554. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  88555. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  88556. this._teleportationTarget.isPickable = false;
  88557. var length = 512;
  88558. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  88559. dynamicTexture.hasAlpha = true;
  88560. var context = dynamicTexture.getContext();
  88561. var centerX = length / 2;
  88562. var centerY = length / 2;
  88563. var radius = 200;
  88564. context.beginPath();
  88565. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  88566. context.fillStyle = this._teleportationFillColor;
  88567. context.fill();
  88568. context.lineWidth = 10;
  88569. context.strokeStyle = this._teleportationBorderColor;
  88570. context.stroke();
  88571. context.closePath();
  88572. dynamicTexture.update();
  88573. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  88574. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  88575. this._teleportationTarget.material = teleportationCircleMaterial;
  88576. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  88577. torus.isPickable = false;
  88578. torus.parent = this._teleportationTarget;
  88579. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88580. var keys = [];
  88581. keys.push({
  88582. frame: 0,
  88583. value: 0
  88584. });
  88585. keys.push({
  88586. frame: 30,
  88587. value: 0.4
  88588. });
  88589. keys.push({
  88590. frame: 60,
  88591. value: 0
  88592. });
  88593. animationInnerCircle.setKeys(keys);
  88594. var easingFunction = new BABYLON.SineEase();
  88595. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88596. animationInnerCircle.setEasingFunction(easingFunction);
  88597. torus.animations = [];
  88598. torus.animations.push(animationInnerCircle);
  88599. this._scene.beginAnimation(torus, 0, 60, true);
  88600. this._hideTeleportationTarget();
  88601. };
  88602. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  88603. this._teleportActive = true;
  88604. if (this._teleportationInitialized) {
  88605. this._teleportationTarget.isVisible = true;
  88606. if (this._isDefaultTeleportationTarget) {
  88607. this._teleportationTarget.getChildren()[0].isVisible = true;
  88608. }
  88609. }
  88610. };
  88611. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  88612. this._teleportActive = false;
  88613. if (this._teleportationInitialized) {
  88614. this._teleportationTarget.isVisible = false;
  88615. if (this._isDefaultTeleportationTarget) {
  88616. this._teleportationTarget.getChildren()[0].isVisible = false;
  88617. }
  88618. }
  88619. };
  88620. VRExperienceHelper.prototype._rotateCamera = function (right) {
  88621. var _this = this;
  88622. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88623. return;
  88624. }
  88625. if (right) {
  88626. this._rotationAngle++;
  88627. }
  88628. else {
  88629. this._rotationAngle--;
  88630. }
  88631. this.currentVRCamera.animations = [];
  88632. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  88633. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88634. var animationRotationKeys = [];
  88635. animationRotationKeys.push({
  88636. frame: 0,
  88637. value: this.currentVRCamera.rotationQuaternion
  88638. });
  88639. animationRotationKeys.push({
  88640. frame: 6,
  88641. value: target
  88642. });
  88643. animationRotation.setKeys(animationRotationKeys);
  88644. animationRotation.setEasingFunction(this._circleEase);
  88645. this.currentVRCamera.animations.push(animationRotation);
  88646. this._postProcessMove.animations = [];
  88647. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88648. var vignetteWeightKeys = [];
  88649. vignetteWeightKeys.push({
  88650. frame: 0,
  88651. value: 0
  88652. });
  88653. vignetteWeightKeys.push({
  88654. frame: 3,
  88655. value: 4
  88656. });
  88657. vignetteWeightKeys.push({
  88658. frame: 6,
  88659. value: 0
  88660. });
  88661. animationPP.setKeys(vignetteWeightKeys);
  88662. animationPP.setEasingFunction(this._circleEase);
  88663. this._postProcessMove.animations.push(animationPP);
  88664. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88665. var vignetteStretchKeys = [];
  88666. vignetteStretchKeys.push({
  88667. frame: 0,
  88668. value: 0
  88669. });
  88670. vignetteStretchKeys.push({
  88671. frame: 3,
  88672. value: 10
  88673. });
  88674. vignetteStretchKeys.push({
  88675. frame: 6,
  88676. value: 0
  88677. });
  88678. animationPP2.setKeys(vignetteStretchKeys);
  88679. animationPP2.setEasingFunction(this._circleEase);
  88680. this._postProcessMove.animations.push(animationPP2);
  88681. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88682. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88683. this._postProcessMove.samples = 4;
  88684. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88685. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  88686. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88687. });
  88688. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  88689. };
  88690. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  88691. if (hit.pickedPoint) {
  88692. if (gazer._teleportationRequestInitiated) {
  88693. this._displayTeleportationTarget();
  88694. this._haloCenter.copyFrom(hit.pickedPoint);
  88695. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  88696. }
  88697. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  88698. if (pickNormal) {
  88699. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88700. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88701. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  88702. }
  88703. this._teleportationTarget.position.y += 0.1;
  88704. }
  88705. };
  88706. VRExperienceHelper.prototype._teleportCamera = function (location) {
  88707. var _this = this;
  88708. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88709. return;
  88710. }
  88711. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  88712. // offset of the headset from the anchor.
  88713. if (this.webVRCamera.leftCamera) {
  88714. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  88715. this._workingVector.subtractInPlace(this.webVRCamera.position);
  88716. location.subtractToRef(this._workingVector, this._workingVector);
  88717. }
  88718. else {
  88719. this._workingVector.copyFrom(location);
  88720. }
  88721. // Add height to account for user's height offset
  88722. if (this.isInVRMode) {
  88723. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  88724. }
  88725. else {
  88726. this._workingVector.y += this._defaultHeight;
  88727. }
  88728. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  88729. // Create animation from the camera's position to the new location
  88730. this.currentVRCamera.animations = [];
  88731. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88732. var animationCameraTeleportationKeys = [{
  88733. frame: 0,
  88734. value: this.currentVRCamera.position
  88735. },
  88736. {
  88737. frame: 11,
  88738. value: this._workingVector
  88739. }
  88740. ];
  88741. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  88742. animationCameraTeleportation.setEasingFunction(this._circleEase);
  88743. this.currentVRCamera.animations.push(animationCameraTeleportation);
  88744. this._postProcessMove.animations = [];
  88745. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88746. var vignetteWeightKeys = [];
  88747. vignetteWeightKeys.push({
  88748. frame: 0,
  88749. value: 0
  88750. });
  88751. vignetteWeightKeys.push({
  88752. frame: 5,
  88753. value: 8
  88754. });
  88755. vignetteWeightKeys.push({
  88756. frame: 11,
  88757. value: 0
  88758. });
  88759. animationPP.setKeys(vignetteWeightKeys);
  88760. this._postProcessMove.animations.push(animationPP);
  88761. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88762. var vignetteStretchKeys = [];
  88763. vignetteStretchKeys.push({
  88764. frame: 0,
  88765. value: 0
  88766. });
  88767. vignetteStretchKeys.push({
  88768. frame: 5,
  88769. value: 10
  88770. });
  88771. vignetteStretchKeys.push({
  88772. frame: 11,
  88773. value: 0
  88774. });
  88775. animationPP2.setKeys(vignetteStretchKeys);
  88776. this._postProcessMove.animations.push(animationPP2);
  88777. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88778. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88779. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88780. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  88781. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88782. });
  88783. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  88784. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  88785. });
  88786. this._hideTeleportationTarget();
  88787. };
  88788. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  88789. if (normal) {
  88790. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  88791. if (angle < Math.PI / 2) {
  88792. normal.scaleInPlace(-1);
  88793. }
  88794. }
  88795. return normal;
  88796. };
  88797. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  88798. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88799. return;
  88800. }
  88801. var ray = gazer._getForwardRay(this._rayLength);
  88802. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88803. // Moving the gazeTracker on the mesh face targetted
  88804. if (hit && hit.pickedPoint) {
  88805. if (this._displayGaze) {
  88806. var multiplier = 1;
  88807. gazer._gazeTracker.isVisible = true;
  88808. if (gazer._isActionableMesh) {
  88809. multiplier = 3;
  88810. }
  88811. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  88812. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  88813. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  88814. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  88815. // To avoid z-fighting
  88816. var deltaFighting = 0.002;
  88817. if (pickNormal) {
  88818. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88819. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88820. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  88821. }
  88822. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  88823. if (gazer._gazeTracker.position.x < 0) {
  88824. gazer._gazeTracker.position.x += deltaFighting;
  88825. }
  88826. else {
  88827. gazer._gazeTracker.position.x -= deltaFighting;
  88828. }
  88829. if (gazer._gazeTracker.position.y < 0) {
  88830. gazer._gazeTracker.position.y += deltaFighting;
  88831. }
  88832. else {
  88833. gazer._gazeTracker.position.y -= deltaFighting;
  88834. }
  88835. if (gazer._gazeTracker.position.z < 0) {
  88836. gazer._gazeTracker.position.z += deltaFighting;
  88837. }
  88838. else {
  88839. gazer._gazeTracker.position.z -= deltaFighting;
  88840. }
  88841. }
  88842. // Changing the size of the laser pointer based on the distance from the targetted point
  88843. gazer._updatePointerDistance(hit.distance);
  88844. }
  88845. else {
  88846. gazer._updatePointerDistance();
  88847. gazer._gazeTracker.isVisible = false;
  88848. }
  88849. if (hit && hit.pickedMesh) {
  88850. gazer._currentHit = hit;
  88851. if (gazer._pointerDownOnMeshAsked) {
  88852. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  88853. }
  88854. // The object selected is the floor, we're in a teleportation scenario
  88855. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  88856. // Moving the teleportation area to this targetted point
  88857. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  88858. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  88859. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88860. }
  88861. gazer._currentMeshSelected = null;
  88862. if (gazer._teleportationRequestInitiated) {
  88863. this._moveTeleportationSelectorTo(hit, gazer, ray);
  88864. }
  88865. return;
  88866. }
  88867. // If not, we're in a selection scenario
  88868. //this._teleportationAllowed = false;
  88869. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  88870. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  88871. this.onNewMeshPicked.notifyObservers(hit);
  88872. gazer._currentMeshSelected = hit.pickedMesh;
  88873. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  88874. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  88875. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  88876. gazer._isActionableMesh = true;
  88877. }
  88878. else {
  88879. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88880. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88881. gazer._isActionableMesh = false;
  88882. }
  88883. try {
  88884. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  88885. }
  88886. catch (err) {
  88887. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  88888. }
  88889. }
  88890. else {
  88891. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88892. gazer._currentMeshSelected = null;
  88893. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88894. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88895. }
  88896. }
  88897. }
  88898. else {
  88899. gazer._currentHit = null;
  88900. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88901. gazer._currentMeshSelected = null;
  88902. //this._teleportationAllowed = false;
  88903. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88904. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88905. }
  88906. };
  88907. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  88908. if (mesh) {
  88909. this.onSelectedMeshUnselected.notifyObservers(mesh);
  88910. }
  88911. };
  88912. /**
  88913. * Sets the color of the laser ray from the vr controllers.
  88914. * @param color new color for the ray.
  88915. */
  88916. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  88917. if (this.leftController) {
  88918. this.leftController._setLaserPointerColor(color);
  88919. }
  88920. if (this.rightController) {
  88921. this.rightController._setLaserPointerColor(color);
  88922. }
  88923. };
  88924. /**
  88925. * Sets the color of the ray from the vr headsets gaze.
  88926. * @param color new color for the ray.
  88927. */
  88928. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  88929. if (!this._cameraGazer._gazeTracker.material) {
  88930. return;
  88931. }
  88932. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  88933. if (this.leftController) {
  88934. this.leftController._gazeTracker.material.emissiveColor = color;
  88935. }
  88936. if (this.rightController) {
  88937. this.rightController._gazeTracker.material.emissiveColor = color;
  88938. }
  88939. };
  88940. /**
  88941. * Exits VR and disposes of the vr experience helper
  88942. */
  88943. VRExperienceHelper.prototype.dispose = function () {
  88944. if (this.isInVRMode) {
  88945. this.exitVR();
  88946. }
  88947. if (this._postProcessMove) {
  88948. this._postProcessMove.dispose();
  88949. }
  88950. if (this._webVRCamera) {
  88951. this._webVRCamera.dispose();
  88952. }
  88953. if (this._vrDeviceOrientationCamera) {
  88954. this._vrDeviceOrientationCamera.dispose();
  88955. }
  88956. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  88957. document.body.removeChild(this._btnVR);
  88958. }
  88959. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  88960. this._deviceOrientationCamera.dispose();
  88961. }
  88962. if (this._cameraGazer) {
  88963. this._cameraGazer.dispose();
  88964. }
  88965. if (this.leftController) {
  88966. this.leftController.dispose();
  88967. }
  88968. if (this.rightController) {
  88969. this.rightController.dispose();
  88970. }
  88971. if (this._teleportationTarget) {
  88972. this._teleportationTarget.dispose();
  88973. }
  88974. this._floorMeshesCollection = [];
  88975. document.removeEventListener("keydown", this._onKeyDown);
  88976. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88977. window.removeEventListener("resize", this._onResize);
  88978. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  88979. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  88980. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  88981. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  88982. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  88983. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  88984. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  88985. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88986. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  88987. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  88988. this._scene.unregisterBeforeRender(this.beforeRender);
  88989. };
  88990. /**
  88991. * Gets the name of the VRExperienceHelper class
  88992. * @returns "VRExperienceHelper"
  88993. */
  88994. VRExperienceHelper.prototype.getClassName = function () {
  88995. return "VRExperienceHelper";
  88996. };
  88997. return VRExperienceHelper;
  88998. }());
  88999. BABYLON.VRExperienceHelper = VRExperienceHelper;
  89000. })(BABYLON || (BABYLON = {}));
  89001. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  89002. // Mainly based on these 2 articles :
  89003. // 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
  89004. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  89005. var BABYLON;
  89006. (function (BABYLON) {
  89007. /**
  89008. * Defines the potential axis of a Joystick
  89009. */
  89010. var JoystickAxis;
  89011. (function (JoystickAxis) {
  89012. /** X axis */
  89013. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  89014. /** Y axis */
  89015. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  89016. /** Z axis */
  89017. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  89018. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  89019. /**
  89020. * Class used to define virtual joystick (used in touch mode)
  89021. */
  89022. var VirtualJoystick = /** @class */ (function () {
  89023. /**
  89024. * Creates a new virtual joystick
  89025. * @param leftJoystick defines that the joystick is for left hand (false by default)
  89026. */
  89027. function VirtualJoystick(leftJoystick) {
  89028. var _this = this;
  89029. if (leftJoystick) {
  89030. this._leftJoystick = true;
  89031. }
  89032. else {
  89033. this._leftJoystick = false;
  89034. }
  89035. VirtualJoystick._globalJoystickIndex++;
  89036. // By default left & right arrow keys are moving the X
  89037. // and up & down keys are moving the Y
  89038. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89039. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89040. this.reverseLeftRight = false;
  89041. this.reverseUpDown = false;
  89042. // collections of pointers
  89043. this._touches = new BABYLON.StringDictionary();
  89044. this.deltaPosition = BABYLON.Vector3.Zero();
  89045. this._joystickSensibility = 25;
  89046. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89047. this._onResize = function (evt) {
  89048. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89049. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89050. if (VirtualJoystick.vjCanvas) {
  89051. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  89052. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  89053. }
  89054. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  89055. };
  89056. // injecting a canvas element on top of the canvas 3D game
  89057. if (!VirtualJoystick.vjCanvas) {
  89058. window.addEventListener("resize", this._onResize, false);
  89059. VirtualJoystick.vjCanvas = document.createElement("canvas");
  89060. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89061. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89062. VirtualJoystick.vjCanvas.width = window.innerWidth;
  89063. VirtualJoystick.vjCanvas.height = window.innerHeight;
  89064. VirtualJoystick.vjCanvas.style.width = "100%";
  89065. VirtualJoystick.vjCanvas.style.height = "100%";
  89066. VirtualJoystick.vjCanvas.style.position = "absolute";
  89067. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  89068. VirtualJoystick.vjCanvas.style.top = "0px";
  89069. VirtualJoystick.vjCanvas.style.left = "0px";
  89070. VirtualJoystick.vjCanvas.style.zIndex = "5";
  89071. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  89072. // Support for jQuery PEP polyfill
  89073. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  89074. var context = VirtualJoystick.vjCanvas.getContext('2d');
  89075. if (!context) {
  89076. throw new Error("Unable to create canvas for virtual joystick");
  89077. }
  89078. VirtualJoystick.vjCanvasContext = context;
  89079. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  89080. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89081. document.body.appendChild(VirtualJoystick.vjCanvas);
  89082. }
  89083. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  89084. this.pressed = false;
  89085. // default joystick color
  89086. this._joystickColor = "cyan";
  89087. this._joystickPointerID = -1;
  89088. // current joystick position
  89089. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  89090. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  89091. // origin joystick position
  89092. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  89093. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  89094. this._onPointerDownHandlerRef = function (evt) {
  89095. _this._onPointerDown(evt);
  89096. };
  89097. this._onPointerMoveHandlerRef = function (evt) {
  89098. _this._onPointerMove(evt);
  89099. };
  89100. this._onPointerUpHandlerRef = function (evt) {
  89101. _this._onPointerUp(evt);
  89102. };
  89103. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  89104. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  89105. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  89106. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  89107. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  89108. evt.preventDefault(); // Disables system menu
  89109. }, false);
  89110. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89111. }
  89112. /**
  89113. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  89114. * @param newJoystickSensibility defines the new sensibility
  89115. */
  89116. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  89117. this._joystickSensibility = newJoystickSensibility;
  89118. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89119. };
  89120. VirtualJoystick.prototype._onPointerDown = function (e) {
  89121. var positionOnScreenCondition;
  89122. e.preventDefault();
  89123. if (this._leftJoystick === true) {
  89124. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  89125. }
  89126. else {
  89127. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  89128. }
  89129. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  89130. // First contact will be dedicated to the virtual joystick
  89131. this._joystickPointerID = e.pointerId;
  89132. this._joystickPointerStartPos.x = e.clientX;
  89133. this._joystickPointerStartPos.y = e.clientY;
  89134. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89135. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89136. this._deltaJoystickVector.x = 0;
  89137. this._deltaJoystickVector.y = 0;
  89138. this.pressed = true;
  89139. this._touches.add(e.pointerId.toString(), e);
  89140. }
  89141. else {
  89142. // You can only trigger the action buttons with a joystick declared
  89143. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89144. this._action();
  89145. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89146. }
  89147. }
  89148. };
  89149. VirtualJoystick.prototype._onPointerMove = function (e) {
  89150. // If the current pointer is the one associated to the joystick (first touch contact)
  89151. if (this._joystickPointerID == e.pointerId) {
  89152. this._joystickPointerPos.x = e.clientX;
  89153. this._joystickPointerPos.y = e.clientY;
  89154. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89155. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89156. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89157. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89158. switch (this._axisTargetedByLeftAndRight) {
  89159. case JoystickAxis.X:
  89160. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89161. break;
  89162. case JoystickAxis.Y:
  89163. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89164. break;
  89165. case JoystickAxis.Z:
  89166. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  89167. break;
  89168. }
  89169. var directionUpDown = this.reverseUpDown ? 1 : -1;
  89170. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  89171. switch (this._axisTargetedByUpAndDown) {
  89172. case JoystickAxis.X:
  89173. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  89174. break;
  89175. case JoystickAxis.Y:
  89176. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  89177. break;
  89178. case JoystickAxis.Z:
  89179. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89180. break;
  89181. }
  89182. }
  89183. else {
  89184. var data = this._touches.get(e.pointerId.toString());
  89185. if (data) {
  89186. data.x = e.clientX;
  89187. data.y = e.clientY;
  89188. }
  89189. }
  89190. };
  89191. VirtualJoystick.prototype._onPointerUp = function (e) {
  89192. if (this._joystickPointerID == e.pointerId) {
  89193. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89194. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89195. this._joystickPointerID = -1;
  89196. this.pressed = false;
  89197. }
  89198. else {
  89199. var touch = this._touches.get(e.pointerId.toString());
  89200. if (touch) {
  89201. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89202. }
  89203. }
  89204. this._deltaJoystickVector.x = 0;
  89205. this._deltaJoystickVector.y = 0;
  89206. this._touches.remove(e.pointerId.toString());
  89207. };
  89208. /**
  89209. * Change the color of the virtual joystick
  89210. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89211. */
  89212. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89213. this._joystickColor = newColor;
  89214. };
  89215. /**
  89216. * Defines a callback to call when the joystick is touched
  89217. * @param action defines the callback
  89218. */
  89219. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89220. this._action = action;
  89221. };
  89222. /**
  89223. * Defines which axis you'd like to control for left & right
  89224. * @param axis defines the axis to use
  89225. */
  89226. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89227. switch (axis) {
  89228. case JoystickAxis.X:
  89229. case JoystickAxis.Y:
  89230. case JoystickAxis.Z:
  89231. this._axisTargetedByLeftAndRight = axis;
  89232. break;
  89233. default:
  89234. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89235. break;
  89236. }
  89237. };
  89238. /**
  89239. * Defines which axis you'd like to control for up & down
  89240. * @param axis defines the axis to use
  89241. */
  89242. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89243. switch (axis) {
  89244. case JoystickAxis.X:
  89245. case JoystickAxis.Y:
  89246. case JoystickAxis.Z:
  89247. this._axisTargetedByUpAndDown = axis;
  89248. break;
  89249. default:
  89250. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89251. break;
  89252. }
  89253. };
  89254. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89255. var _this = this;
  89256. if (this.pressed) {
  89257. this._touches.forEach(function (key, touch) {
  89258. if (touch.pointerId === _this._joystickPointerID) {
  89259. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89260. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89261. VirtualJoystick.vjCanvasContext.beginPath();
  89262. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89263. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89264. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89265. VirtualJoystick.vjCanvasContext.stroke();
  89266. VirtualJoystick.vjCanvasContext.closePath();
  89267. VirtualJoystick.vjCanvasContext.beginPath();
  89268. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89269. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89270. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89271. VirtualJoystick.vjCanvasContext.stroke();
  89272. VirtualJoystick.vjCanvasContext.closePath();
  89273. VirtualJoystick.vjCanvasContext.beginPath();
  89274. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89275. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89276. VirtualJoystick.vjCanvasContext.stroke();
  89277. VirtualJoystick.vjCanvasContext.closePath();
  89278. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89279. }
  89280. else {
  89281. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89282. VirtualJoystick.vjCanvasContext.beginPath();
  89283. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89284. VirtualJoystick.vjCanvasContext.beginPath();
  89285. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89286. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89287. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89288. VirtualJoystick.vjCanvasContext.stroke();
  89289. VirtualJoystick.vjCanvasContext.closePath();
  89290. touch.prevX = touch.x;
  89291. touch.prevY = touch.y;
  89292. }
  89293. ;
  89294. });
  89295. }
  89296. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89297. };
  89298. /**
  89299. * Release internal HTML canvas
  89300. */
  89301. VirtualJoystick.prototype.releaseCanvas = function () {
  89302. if (VirtualJoystick.vjCanvas) {
  89303. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89304. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89305. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89306. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89307. window.removeEventListener("resize", this._onResize);
  89308. document.body.removeChild(VirtualJoystick.vjCanvas);
  89309. VirtualJoystick.vjCanvas = null;
  89310. }
  89311. };
  89312. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89313. VirtualJoystick._globalJoystickIndex = 0;
  89314. return VirtualJoystick;
  89315. }());
  89316. BABYLON.VirtualJoystick = VirtualJoystick;
  89317. })(BABYLON || (BABYLON = {}));
  89318. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89319. var BABYLON;
  89320. (function (BABYLON) {
  89321. // We're mainly based on the logic defined into the FreeCamera code
  89322. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89323. __extends(VirtualJoysticksCamera, _super);
  89324. function VirtualJoysticksCamera(name, position, scene) {
  89325. var _this = _super.call(this, name, position, scene) || this;
  89326. _this.inputs.addVirtualJoystick();
  89327. return _this;
  89328. }
  89329. VirtualJoysticksCamera.prototype.getClassName = function () {
  89330. return "VirtualJoysticksCamera";
  89331. };
  89332. return VirtualJoysticksCamera;
  89333. }(BABYLON.FreeCamera));
  89334. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  89335. })(BABYLON || (BABYLON = {}));
  89336. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  89337. var BABYLON;
  89338. (function (BABYLON) {
  89339. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  89340. function FreeCameraVirtualJoystickInput() {
  89341. }
  89342. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  89343. return this._leftjoystick;
  89344. };
  89345. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  89346. return this._rightjoystick;
  89347. };
  89348. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  89349. if (this._leftjoystick) {
  89350. var camera = this.camera;
  89351. var speed = camera._computeLocalCameraSpeed() * 50;
  89352. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  89353. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  89354. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  89355. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  89356. if (!this._leftjoystick.pressed) {
  89357. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  89358. }
  89359. if (!this._rightjoystick.pressed) {
  89360. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  89361. }
  89362. }
  89363. };
  89364. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  89365. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  89366. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  89367. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  89368. this._leftjoystick.setJoystickSensibility(0.15);
  89369. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  89370. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  89371. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  89372. this._rightjoystick.reverseUpDown = true;
  89373. this._rightjoystick.setJoystickSensibility(0.05);
  89374. this._rightjoystick.setJoystickColor("yellow");
  89375. };
  89376. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  89377. this._leftjoystick.releaseCanvas();
  89378. this._rightjoystick.releaseCanvas();
  89379. };
  89380. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  89381. return "FreeCameraVirtualJoystickInput";
  89382. };
  89383. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  89384. return "virtualJoystick";
  89385. };
  89386. return FreeCameraVirtualJoystickInput;
  89387. }());
  89388. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  89389. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  89390. })(BABYLON || (BABYLON = {}));
  89391. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  89392. var BABYLON;
  89393. (function (BABYLON) {
  89394. var SimplificationSettings = /** @class */ (function () {
  89395. function SimplificationSettings(quality, distance, optimizeMesh) {
  89396. this.quality = quality;
  89397. this.distance = distance;
  89398. this.optimizeMesh = optimizeMesh;
  89399. }
  89400. return SimplificationSettings;
  89401. }());
  89402. BABYLON.SimplificationSettings = SimplificationSettings;
  89403. var SimplificationQueue = /** @class */ (function () {
  89404. function SimplificationQueue() {
  89405. this.running = false;
  89406. this._simplificationArray = [];
  89407. }
  89408. SimplificationQueue.prototype.addTask = function (task) {
  89409. this._simplificationArray.push(task);
  89410. };
  89411. SimplificationQueue.prototype.executeNext = function () {
  89412. var task = this._simplificationArray.pop();
  89413. if (task) {
  89414. this.running = true;
  89415. this.runSimplification(task);
  89416. }
  89417. else {
  89418. this.running = false;
  89419. }
  89420. };
  89421. SimplificationQueue.prototype.runSimplification = function (task) {
  89422. var _this = this;
  89423. if (task.parallelProcessing) {
  89424. //parallel simplifier
  89425. task.settings.forEach(function (setting) {
  89426. var simplifier = _this.getSimplifier(task);
  89427. simplifier.simplify(setting, function (newMesh) {
  89428. task.mesh.addLODLevel(setting.distance, newMesh);
  89429. newMesh.isVisible = true;
  89430. //check if it is the last
  89431. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  89432. //all done, run the success callback.
  89433. task.successCallback();
  89434. }
  89435. _this.executeNext();
  89436. });
  89437. });
  89438. }
  89439. else {
  89440. //single simplifier.
  89441. var simplifier = this.getSimplifier(task);
  89442. var runDecimation = function (setting, callback) {
  89443. simplifier.simplify(setting, function (newMesh) {
  89444. task.mesh.addLODLevel(setting.distance, newMesh);
  89445. newMesh.isVisible = true;
  89446. //run the next quality level
  89447. callback();
  89448. });
  89449. };
  89450. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  89451. runDecimation(task.settings[loop.index], function () {
  89452. loop.executeNext();
  89453. });
  89454. }, function () {
  89455. //execution ended, run the success callback.
  89456. if (task.successCallback) {
  89457. task.successCallback();
  89458. }
  89459. _this.executeNext();
  89460. });
  89461. }
  89462. };
  89463. SimplificationQueue.prototype.getSimplifier = function (task) {
  89464. switch (task.simplificationType) {
  89465. case SimplificationType.QUADRATIC:
  89466. default:
  89467. return new QuadraticErrorSimplification(task.mesh);
  89468. }
  89469. };
  89470. return SimplificationQueue;
  89471. }());
  89472. BABYLON.SimplificationQueue = SimplificationQueue;
  89473. /**
  89474. * The implemented types of simplification
  89475. * At the moment only Quadratic Error Decimation is implemented
  89476. */
  89477. var SimplificationType;
  89478. (function (SimplificationType) {
  89479. /** Quadratic error decimation */
  89480. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  89481. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  89482. var DecimationTriangle = /** @class */ (function () {
  89483. function DecimationTriangle(vertices) {
  89484. this.vertices = vertices;
  89485. this.error = new Array(4);
  89486. this.deleted = false;
  89487. this.isDirty = false;
  89488. this.deletePending = false;
  89489. this.borderFactor = 0;
  89490. }
  89491. return DecimationTriangle;
  89492. }());
  89493. BABYLON.DecimationTriangle = DecimationTriangle;
  89494. var DecimationVertex = /** @class */ (function () {
  89495. function DecimationVertex(position, id) {
  89496. this.position = position;
  89497. this.id = id;
  89498. this.isBorder = true;
  89499. this.q = new QuadraticMatrix();
  89500. this.triangleCount = 0;
  89501. this.triangleStart = 0;
  89502. this.originalOffsets = [];
  89503. }
  89504. DecimationVertex.prototype.updatePosition = function (newPosition) {
  89505. this.position.copyFrom(newPosition);
  89506. };
  89507. return DecimationVertex;
  89508. }());
  89509. BABYLON.DecimationVertex = DecimationVertex;
  89510. var QuadraticMatrix = /** @class */ (function () {
  89511. function QuadraticMatrix(data) {
  89512. this.data = new Array(10);
  89513. for (var i = 0; i < 10; ++i) {
  89514. if (data && data[i]) {
  89515. this.data[i] = data[i];
  89516. }
  89517. else {
  89518. this.data[i] = 0;
  89519. }
  89520. }
  89521. }
  89522. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  89523. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  89524. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  89525. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  89526. return det;
  89527. };
  89528. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  89529. for (var i = 0; i < 10; ++i) {
  89530. this.data[i] += matrix.data[i];
  89531. }
  89532. };
  89533. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  89534. for (var i = 0; i < 10; ++i) {
  89535. this.data[i] += data[i];
  89536. }
  89537. };
  89538. QuadraticMatrix.prototype.add = function (matrix) {
  89539. var m = new QuadraticMatrix();
  89540. for (var i = 0; i < 10; ++i) {
  89541. m.data[i] = this.data[i] + matrix.data[i];
  89542. }
  89543. return m;
  89544. };
  89545. QuadraticMatrix.FromData = function (a, b, c, d) {
  89546. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  89547. };
  89548. //returning an array to avoid garbage collection
  89549. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  89550. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  89551. };
  89552. return QuadraticMatrix;
  89553. }());
  89554. BABYLON.QuadraticMatrix = QuadraticMatrix;
  89555. var Reference = /** @class */ (function () {
  89556. function Reference(vertexId, triangleId) {
  89557. this.vertexId = vertexId;
  89558. this.triangleId = triangleId;
  89559. }
  89560. return Reference;
  89561. }());
  89562. BABYLON.Reference = Reference;
  89563. /**
  89564. * An implementation of the Quadratic Error simplification algorithm.
  89565. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  89566. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  89567. * @author RaananW
  89568. */
  89569. var QuadraticErrorSimplification = /** @class */ (function () {
  89570. function QuadraticErrorSimplification(_mesh) {
  89571. this._mesh = _mesh;
  89572. this.syncIterations = 5000;
  89573. this.aggressiveness = 7;
  89574. this.decimationIterations = 100;
  89575. this.boundingBoxEpsilon = BABYLON.Epsilon;
  89576. }
  89577. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  89578. var _this = this;
  89579. this.initDecimatedMesh();
  89580. //iterating through the submeshes array, one after the other.
  89581. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  89582. _this.initWithMesh(loop.index, function () {
  89583. _this.runDecimation(settings, loop.index, function () {
  89584. loop.executeNext();
  89585. });
  89586. }, settings.optimizeMesh);
  89587. }, function () {
  89588. setTimeout(function () {
  89589. successCallback(_this._reconstructedMesh);
  89590. }, 0);
  89591. });
  89592. };
  89593. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  89594. var _this = this;
  89595. var targetCount = ~~(this.triangles.length * settings.quality);
  89596. var deletedTriangles = 0;
  89597. var triangleCount = this.triangles.length;
  89598. var iterationFunction = function (iteration, callback) {
  89599. setTimeout(function () {
  89600. if (iteration % 5 === 0) {
  89601. _this.updateMesh(iteration === 0);
  89602. }
  89603. for (var i = 0; i < _this.triangles.length; ++i) {
  89604. _this.triangles[i].isDirty = false;
  89605. }
  89606. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  89607. var trianglesIterator = function (i) {
  89608. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  89609. var t = _this.triangles[tIdx];
  89610. if (!t)
  89611. return;
  89612. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  89613. return;
  89614. }
  89615. for (var j = 0; j < 3; ++j) {
  89616. if (t.error[j] < threshold) {
  89617. var deleted0 = [];
  89618. var deleted1 = [];
  89619. var v0 = t.vertices[j];
  89620. var v1 = t.vertices[(j + 1) % 3];
  89621. if (v0.isBorder || v1.isBorder)
  89622. continue;
  89623. var p = BABYLON.Vector3.Zero();
  89624. var n = BABYLON.Vector3.Zero();
  89625. var uv = BABYLON.Vector2.Zero();
  89626. var color = new BABYLON.Color4(0, 0, 0, 1);
  89627. _this.calculateError(v0, v1, p, n, uv, color);
  89628. var delTr = new Array();
  89629. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  89630. continue;
  89631. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  89632. continue;
  89633. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  89634. continue;
  89635. var uniqueArray = new Array();
  89636. delTr.forEach(function (deletedT) {
  89637. if (uniqueArray.indexOf(deletedT) === -1) {
  89638. deletedT.deletePending = true;
  89639. uniqueArray.push(deletedT);
  89640. }
  89641. });
  89642. if (uniqueArray.length % 2 !== 0) {
  89643. continue;
  89644. }
  89645. v0.q = v1.q.add(v0.q);
  89646. v0.updatePosition(p);
  89647. var tStart = _this.references.length;
  89648. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  89649. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  89650. var tCount = _this.references.length - tStart;
  89651. if (tCount <= v0.triangleCount) {
  89652. if (tCount) {
  89653. for (var c = 0; c < tCount; c++) {
  89654. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  89655. }
  89656. }
  89657. }
  89658. else {
  89659. v0.triangleStart = tStart;
  89660. }
  89661. v0.triangleCount = tCount;
  89662. break;
  89663. }
  89664. }
  89665. };
  89666. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  89667. }, 0);
  89668. };
  89669. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  89670. if (triangleCount - deletedTriangles <= targetCount)
  89671. loop.breakLoop();
  89672. else {
  89673. iterationFunction(loop.index, function () {
  89674. loop.executeNext();
  89675. });
  89676. }
  89677. }, function () {
  89678. setTimeout(function () {
  89679. //reconstruct this part of the mesh
  89680. _this.reconstructMesh(submeshIndex);
  89681. successCallback();
  89682. }, 0);
  89683. });
  89684. };
  89685. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  89686. var _this = this;
  89687. this.vertices = [];
  89688. this.triangles = [];
  89689. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89690. var indices = this._mesh.getIndices();
  89691. var submesh = this._mesh.subMeshes[submeshIndex];
  89692. var findInVertices = function (positionToSearch) {
  89693. if (optimizeMesh) {
  89694. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  89695. if (_this.vertices[ii].position.equals(positionToSearch)) {
  89696. return _this.vertices[ii];
  89697. }
  89698. }
  89699. }
  89700. return null;
  89701. };
  89702. var vertexReferences = [];
  89703. var vertexInit = function (i) {
  89704. if (!positionData) {
  89705. return;
  89706. }
  89707. var offset = i + submesh.verticesStart;
  89708. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  89709. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  89710. vertex.originalOffsets.push(offset);
  89711. if (vertex.id === _this.vertices.length) {
  89712. _this.vertices.push(vertex);
  89713. }
  89714. vertexReferences.push(vertex.id);
  89715. };
  89716. //var totalVertices = mesh.getTotalVertices();
  89717. var totalVertices = submesh.verticesCount;
  89718. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  89719. var indicesInit = function (i) {
  89720. if (!indices) {
  89721. return;
  89722. }
  89723. var offset = (submesh.indexStart / 3) + i;
  89724. var pos = (offset * 3);
  89725. var i0 = indices[pos + 0];
  89726. var i1 = indices[pos + 1];
  89727. var i2 = indices[pos + 2];
  89728. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  89729. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  89730. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  89731. var triangle = new DecimationTriangle([v0, v1, v2]);
  89732. triangle.originalOffset = pos;
  89733. _this.triangles.push(triangle);
  89734. };
  89735. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  89736. _this.init(callback);
  89737. });
  89738. });
  89739. };
  89740. QuadraticErrorSimplification.prototype.init = function (callback) {
  89741. var _this = this;
  89742. var triangleInit1 = function (i) {
  89743. var t = _this.triangles[i];
  89744. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  89745. for (var j = 0; j < 3; j++) {
  89746. 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))));
  89747. }
  89748. };
  89749. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  89750. var triangleInit2 = function (i) {
  89751. var t = _this.triangles[i];
  89752. for (var j = 0; j < 3; ++j) {
  89753. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  89754. }
  89755. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89756. };
  89757. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  89758. callback();
  89759. });
  89760. });
  89761. };
  89762. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89763. var newTriangles = [];
  89764. var i;
  89765. for (i = 0; i < this.vertices.length; ++i) {
  89766. this.vertices[i].triangleCount = 0;
  89767. }
  89768. var t;
  89769. var j;
  89770. for (i = 0; i < this.triangles.length; ++i) {
  89771. if (!this.triangles[i].deleted) {
  89772. t = this.triangles[i];
  89773. for (j = 0; j < 3; ++j) {
  89774. t.vertices[j].triangleCount = 1;
  89775. }
  89776. newTriangles.push(t);
  89777. }
  89778. }
  89779. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  89780. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  89781. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  89782. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  89783. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  89784. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89785. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  89786. var vertexCount = 0;
  89787. for (i = 0; i < this.vertices.length; ++i) {
  89788. var vertex = this.vertices[i];
  89789. vertex.id = vertexCount;
  89790. if (vertex.triangleCount) {
  89791. vertex.originalOffsets.forEach(function (originalOffset) {
  89792. if (!normalData) {
  89793. return;
  89794. }
  89795. newPositionData.push(vertex.position.x);
  89796. newPositionData.push(vertex.position.y);
  89797. newPositionData.push(vertex.position.z);
  89798. newNormalData.push(normalData[originalOffset * 3]);
  89799. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  89800. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  89801. if (uvs && uvs.length) {
  89802. newUVsData.push(uvs[(originalOffset * 2)]);
  89803. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  89804. }
  89805. else if (colorsData && colorsData.length) {
  89806. newColorsData.push(colorsData[(originalOffset * 4)]);
  89807. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  89808. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  89809. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  89810. }
  89811. ++vertexCount;
  89812. });
  89813. }
  89814. }
  89815. var startingIndex = this._reconstructedMesh.getTotalIndices();
  89816. var startingVertex = this._reconstructedMesh.getTotalVertices();
  89817. var submeshesArray = this._reconstructedMesh.subMeshes;
  89818. this._reconstructedMesh.subMeshes = [];
  89819. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  89820. var originalIndices = this._mesh.getIndices();
  89821. for (i = 0; i < newTriangles.length; ++i) {
  89822. t = newTriangles[i]; //now get the new referencing point for each vertex
  89823. [0, 1, 2].forEach(function (idx) {
  89824. var id = originalIndices[t.originalOffset + idx];
  89825. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  89826. if (offset < 0)
  89827. offset = 0;
  89828. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  89829. });
  89830. }
  89831. //overwriting the old vertex buffers and indices.
  89832. this._reconstructedMesh.setIndices(newIndicesArray);
  89833. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  89834. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  89835. if (newUVsData.length > 0)
  89836. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  89837. if (newColorsData.length > 0)
  89838. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  89839. //create submesh
  89840. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  89841. if (submeshIndex > 0) {
  89842. this._reconstructedMesh.subMeshes = [];
  89843. submeshesArray.forEach(function (submesh) {
  89844. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  89845. });
  89846. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  89847. }
  89848. };
  89849. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  89850. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  89851. this._reconstructedMesh.material = this._mesh.material;
  89852. this._reconstructedMesh.parent = this._mesh.parent;
  89853. this._reconstructedMesh.isVisible = false;
  89854. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  89855. };
  89856. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  89857. for (var i = 0; i < vertex1.triangleCount; ++i) {
  89858. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  89859. if (t.deleted)
  89860. continue;
  89861. var s = this.references[vertex1.triangleStart + i].vertexId;
  89862. var v1 = t.vertices[(s + 1) % 3];
  89863. var v2 = t.vertices[(s + 2) % 3];
  89864. if ((v1 === vertex2 || v2 === vertex2)) {
  89865. deletedArray[i] = true;
  89866. delTr.push(t);
  89867. continue;
  89868. }
  89869. var d1 = v1.position.subtract(point);
  89870. d1 = d1.normalize();
  89871. var d2 = v2.position.subtract(point);
  89872. d2 = d2.normalize();
  89873. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  89874. return true;
  89875. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  89876. deletedArray[i] = false;
  89877. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  89878. return true;
  89879. }
  89880. return false;
  89881. };
  89882. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  89883. var newDeleted = deletedTriangles;
  89884. for (var i = 0; i < vertex.triangleCount; ++i) {
  89885. var ref = this.references[vertex.triangleStart + i];
  89886. var t = this.triangles[ref.triangleId];
  89887. if (t.deleted)
  89888. continue;
  89889. if (deletedArray[i] && t.deletePending) {
  89890. t.deleted = true;
  89891. newDeleted++;
  89892. continue;
  89893. }
  89894. t.vertices[ref.vertexId] = origVertex;
  89895. t.isDirty = true;
  89896. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  89897. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  89898. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  89899. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89900. this.references.push(ref);
  89901. }
  89902. return newDeleted;
  89903. };
  89904. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  89905. for (var i = 0; i < this.vertices.length; ++i) {
  89906. var vCount = [];
  89907. var vId = [];
  89908. var v = this.vertices[i];
  89909. var j;
  89910. for (j = 0; j < v.triangleCount; ++j) {
  89911. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  89912. for (var ii = 0; ii < 3; ii++) {
  89913. var ofs = 0;
  89914. var vv = triangle.vertices[ii];
  89915. while (ofs < vCount.length) {
  89916. if (vId[ofs] === vv.id)
  89917. break;
  89918. ++ofs;
  89919. }
  89920. if (ofs === vCount.length) {
  89921. vCount.push(1);
  89922. vId.push(vv.id);
  89923. }
  89924. else {
  89925. vCount[ofs]++;
  89926. }
  89927. }
  89928. }
  89929. for (j = 0; j < vCount.length; ++j) {
  89930. if (vCount[j] === 1) {
  89931. this.vertices[vId[j]].isBorder = true;
  89932. }
  89933. else {
  89934. this.vertices[vId[j]].isBorder = false;
  89935. }
  89936. }
  89937. }
  89938. };
  89939. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  89940. if (identifyBorders === void 0) { identifyBorders = false; }
  89941. var i;
  89942. if (!identifyBorders) {
  89943. var newTrianglesVector = [];
  89944. for (i = 0; i < this.triangles.length; ++i) {
  89945. if (!this.triangles[i].deleted) {
  89946. newTrianglesVector.push(this.triangles[i]);
  89947. }
  89948. }
  89949. this.triangles = newTrianglesVector;
  89950. }
  89951. for (i = 0; i < this.vertices.length; ++i) {
  89952. this.vertices[i].triangleCount = 0;
  89953. this.vertices[i].triangleStart = 0;
  89954. }
  89955. var t;
  89956. var j;
  89957. var v;
  89958. for (i = 0; i < this.triangles.length; ++i) {
  89959. t = this.triangles[i];
  89960. for (j = 0; j < 3; ++j) {
  89961. v = t.vertices[j];
  89962. v.triangleCount++;
  89963. }
  89964. }
  89965. var tStart = 0;
  89966. for (i = 0; i < this.vertices.length; ++i) {
  89967. this.vertices[i].triangleStart = tStart;
  89968. tStart += this.vertices[i].triangleCount;
  89969. this.vertices[i].triangleCount = 0;
  89970. }
  89971. var newReferences = new Array(this.triangles.length * 3);
  89972. for (i = 0; i < this.triangles.length; ++i) {
  89973. t = this.triangles[i];
  89974. for (j = 0; j < 3; ++j) {
  89975. v = t.vertices[j];
  89976. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  89977. v.triangleCount++;
  89978. }
  89979. }
  89980. this.references = newReferences;
  89981. if (identifyBorders) {
  89982. this.identifyBorder();
  89983. }
  89984. };
  89985. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  89986. var x = point.x;
  89987. var y = point.y;
  89988. var z = point.z;
  89989. 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
  89990. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  89991. };
  89992. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  89993. var q = vertex1.q.add(vertex2.q);
  89994. var border = vertex1.isBorder && vertex2.isBorder;
  89995. var error = 0;
  89996. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  89997. if (qDet !== 0 && !border) {
  89998. if (!pointResult) {
  89999. pointResult = BABYLON.Vector3.Zero();
  90000. }
  90001. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  90002. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  90003. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  90004. error = this.vertexError(q, pointResult);
  90005. }
  90006. else {
  90007. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  90008. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  90009. var error1 = this.vertexError(q, vertex1.position);
  90010. var error2 = this.vertexError(q, vertex2.position);
  90011. var error3 = this.vertexError(q, p3);
  90012. error = Math.min(error1, error2, error3);
  90013. if (error === error1) {
  90014. if (pointResult) {
  90015. pointResult.copyFrom(vertex1.position);
  90016. }
  90017. }
  90018. else if (error === error2) {
  90019. if (pointResult) {
  90020. pointResult.copyFrom(vertex2.position);
  90021. }
  90022. }
  90023. else {
  90024. if (pointResult) {
  90025. pointResult.copyFrom(p3);
  90026. }
  90027. }
  90028. }
  90029. return error;
  90030. };
  90031. return QuadraticErrorSimplification;
  90032. }());
  90033. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  90034. })(BABYLON || (BABYLON = {}));
  90035. //# sourceMappingURL=babylon.meshSimplification.js.map
  90036. var BABYLON;
  90037. (function (BABYLON) {
  90038. var MeshLODLevel = /** @class */ (function () {
  90039. function MeshLODLevel(distance, mesh) {
  90040. this.distance = distance;
  90041. this.mesh = mesh;
  90042. }
  90043. return MeshLODLevel;
  90044. }());
  90045. BABYLON.MeshLODLevel = MeshLODLevel;
  90046. })(BABYLON || (BABYLON = {}));
  90047. //# sourceMappingURL=babylon.meshLODLevel.js.map
  90048. var BABYLON;
  90049. (function (BABYLON) {
  90050. /**
  90051. * Defines the root class used to create scene optimization to use with SceneOptimizer
  90052. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90053. */
  90054. var SceneOptimization = /** @class */ (function () {
  90055. /**
  90056. * Creates the SceneOptimization object
  90057. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90058. * @param desc defines the description associated with the optimization
  90059. */
  90060. function SceneOptimization(
  90061. /**
  90062. * Defines the priority of this optimization (0 by default which means first in the list)
  90063. */
  90064. priority) {
  90065. if (priority === void 0) { priority = 0; }
  90066. this.priority = priority;
  90067. }
  90068. /**
  90069. * Gets a string describing the action executed by the current optimization
  90070. * @returns description string
  90071. */
  90072. SceneOptimization.prototype.getDescription = function () {
  90073. return "";
  90074. };
  90075. /**
  90076. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90077. * @param scene defines the current scene where to apply this optimization
  90078. * @param optimizer defines the current optimizer
  90079. * @returns true if everything that can be done was applied
  90080. */
  90081. SceneOptimization.prototype.apply = function (scene, optimizer) {
  90082. return true;
  90083. };
  90084. ;
  90085. return SceneOptimization;
  90086. }());
  90087. BABYLON.SceneOptimization = SceneOptimization;
  90088. /**
  90089. * Defines an optimization used to reduce the size of render target textures
  90090. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90091. */
  90092. var TextureOptimization = /** @class */ (function (_super) {
  90093. __extends(TextureOptimization, _super);
  90094. /**
  90095. * Creates the TextureOptimization object
  90096. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90097. * @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
  90098. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90099. */
  90100. function TextureOptimization(
  90101. /**
  90102. * Defines the priority of this optimization (0 by default which means first in the list)
  90103. */
  90104. priority,
  90105. /**
  90106. * 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
  90107. */
  90108. maximumSize,
  90109. /**
  90110. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90111. */
  90112. step) {
  90113. if (priority === void 0) { priority = 0; }
  90114. if (maximumSize === void 0) { maximumSize = 1024; }
  90115. if (step === void 0) { step = 0.5; }
  90116. var _this = _super.call(this, priority) || this;
  90117. _this.priority = priority;
  90118. _this.maximumSize = maximumSize;
  90119. _this.step = step;
  90120. return _this;
  90121. }
  90122. /**
  90123. * Gets a string describing the action executed by the current optimization
  90124. * @returns description string
  90125. */
  90126. TextureOptimization.prototype.getDescription = function () {
  90127. return "Reducing render target texture size to " + this.maximumSize;
  90128. };
  90129. /**
  90130. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90131. * @param scene defines the current scene where to apply this optimization
  90132. * @param optimizer defines the current optimizer
  90133. * @returns true if everything that can be done was applied
  90134. */
  90135. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90136. var allDone = true;
  90137. for (var index = 0; index < scene.textures.length; index++) {
  90138. var texture = scene.textures[index];
  90139. if (!texture.canRescale || texture.getContext) {
  90140. continue;
  90141. }
  90142. var currentSize = texture.getSize();
  90143. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90144. if (maxDimension > this.maximumSize) {
  90145. texture.scale(this.step);
  90146. allDone = false;
  90147. }
  90148. }
  90149. return allDone;
  90150. };
  90151. return TextureOptimization;
  90152. }(SceneOptimization));
  90153. BABYLON.TextureOptimization = TextureOptimization;
  90154. /**
  90155. * Defines an optimization used to increase or decrease the rendering resolution
  90156. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90157. */
  90158. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90159. __extends(HardwareScalingOptimization, _super);
  90160. /**
  90161. * Creates the HardwareScalingOptimization object
  90162. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90163. * @param maximumScale defines the maximum scale to use (2 by default)
  90164. * @param step defines the step to use between two passes (0.5 by default)
  90165. */
  90166. function HardwareScalingOptimization(
  90167. /**
  90168. * Defines the priority of this optimization (0 by default which means first in the list)
  90169. */
  90170. priority,
  90171. /**
  90172. * Defines the maximum scale to use (2 by default)
  90173. */
  90174. maximumScale,
  90175. /**
  90176. * Defines the step to use between two passes (0.5 by default)
  90177. */
  90178. step) {
  90179. if (priority === void 0) { priority = 0; }
  90180. if (maximumScale === void 0) { maximumScale = 2; }
  90181. if (step === void 0) { step = 0.25; }
  90182. var _this = _super.call(this, priority) || this;
  90183. _this.priority = priority;
  90184. _this.maximumScale = maximumScale;
  90185. _this.step = step;
  90186. _this._currentScale = -1;
  90187. _this._directionOffset = 1;
  90188. return _this;
  90189. }
  90190. /**
  90191. * Gets a string describing the action executed by the current optimization
  90192. * @return description string
  90193. */
  90194. HardwareScalingOptimization.prototype.getDescription = function () {
  90195. return "Setting hardware scaling level to " + this._currentScale;
  90196. };
  90197. /**
  90198. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90199. * @param scene defines the current scene where to apply this optimization
  90200. * @param optimizer defines the current optimizer
  90201. * @returns true if everything that can be done was applied
  90202. */
  90203. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90204. if (this._currentScale === -1) {
  90205. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90206. if (this._currentScale > this.maximumScale) {
  90207. this._directionOffset = -1;
  90208. }
  90209. }
  90210. this._currentScale += this._directionOffset * this.step;
  90211. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90212. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90213. };
  90214. ;
  90215. return HardwareScalingOptimization;
  90216. }(SceneOptimization));
  90217. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90218. /**
  90219. * Defines an optimization used to remove shadows
  90220. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90221. */
  90222. var ShadowsOptimization = /** @class */ (function (_super) {
  90223. __extends(ShadowsOptimization, _super);
  90224. function ShadowsOptimization() {
  90225. return _super !== null && _super.apply(this, arguments) || this;
  90226. }
  90227. /**
  90228. * Gets a string describing the action executed by the current optimization
  90229. * @return description string
  90230. */
  90231. ShadowsOptimization.prototype.getDescription = function () {
  90232. return "Turning shadows on/off";
  90233. };
  90234. /**
  90235. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90236. * @param scene defines the current scene where to apply this optimization
  90237. * @param optimizer defines the current optimizer
  90238. * @returns true if everything that can be done was applied
  90239. */
  90240. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90241. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90242. return true;
  90243. };
  90244. ;
  90245. return ShadowsOptimization;
  90246. }(SceneOptimization));
  90247. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90248. /**
  90249. * Defines an optimization used to turn post-processes off
  90250. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90251. */
  90252. var PostProcessesOptimization = /** @class */ (function (_super) {
  90253. __extends(PostProcessesOptimization, _super);
  90254. function PostProcessesOptimization() {
  90255. return _super !== null && _super.apply(this, arguments) || this;
  90256. }
  90257. /**
  90258. * Gets a string describing the action executed by the current optimization
  90259. * @return description string
  90260. */
  90261. PostProcessesOptimization.prototype.getDescription = function () {
  90262. return "Turning post-processes on/off";
  90263. };
  90264. /**
  90265. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90266. * @param scene defines the current scene where to apply this optimization
  90267. * @param optimizer defines the current optimizer
  90268. * @returns true if everything that can be done was applied
  90269. */
  90270. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90271. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90272. return true;
  90273. };
  90274. ;
  90275. return PostProcessesOptimization;
  90276. }(SceneOptimization));
  90277. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90278. /**
  90279. * Defines an optimization used to turn lens flares off
  90280. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90281. */
  90282. var LensFlaresOptimization = /** @class */ (function (_super) {
  90283. __extends(LensFlaresOptimization, _super);
  90284. function LensFlaresOptimization() {
  90285. return _super !== null && _super.apply(this, arguments) || this;
  90286. }
  90287. /**
  90288. * Gets a string describing the action executed by the current optimization
  90289. * @return description string
  90290. */
  90291. LensFlaresOptimization.prototype.getDescription = function () {
  90292. return "Turning lens flares on/off";
  90293. };
  90294. /**
  90295. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90296. * @param scene defines the current scene where to apply this optimization
  90297. * @param optimizer defines the current optimizer
  90298. * @returns true if everything that can be done was applied
  90299. */
  90300. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90301. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90302. return true;
  90303. };
  90304. ;
  90305. return LensFlaresOptimization;
  90306. }(SceneOptimization));
  90307. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90308. /**
  90309. * Defines an optimization based on user defined callback.
  90310. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90311. */
  90312. var CustomOptimization = /** @class */ (function (_super) {
  90313. __extends(CustomOptimization, _super);
  90314. function CustomOptimization() {
  90315. return _super !== null && _super.apply(this, arguments) || this;
  90316. }
  90317. /**
  90318. * Gets a string describing the action executed by the current optimization
  90319. * @returns description string
  90320. */
  90321. CustomOptimization.prototype.getDescription = function () {
  90322. if (this.onGetDescription) {
  90323. return this.onGetDescription();
  90324. }
  90325. return "Running user defined callback";
  90326. };
  90327. /**
  90328. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90329. * @param scene defines the current scene where to apply this optimization
  90330. * @param optimizer defines the current optimizer
  90331. * @returns true if everything that can be done was applied
  90332. */
  90333. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90334. if (this.onApply) {
  90335. return this.onApply(scene, optimizer);
  90336. }
  90337. return true;
  90338. };
  90339. ;
  90340. return CustomOptimization;
  90341. }(SceneOptimization));
  90342. BABYLON.CustomOptimization = CustomOptimization;
  90343. /**
  90344. * Defines an optimization used to turn particles off
  90345. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90346. */
  90347. var ParticlesOptimization = /** @class */ (function (_super) {
  90348. __extends(ParticlesOptimization, _super);
  90349. function ParticlesOptimization() {
  90350. return _super !== null && _super.apply(this, arguments) || this;
  90351. }
  90352. /**
  90353. * Gets a string describing the action executed by the current optimization
  90354. * @return description string
  90355. */
  90356. ParticlesOptimization.prototype.getDescription = function () {
  90357. return "Turning particles on/off";
  90358. };
  90359. /**
  90360. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90361. * @param scene defines the current scene where to apply this optimization
  90362. * @param optimizer defines the current optimizer
  90363. * @returns true if everything that can be done was applied
  90364. */
  90365. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  90366. scene.particlesEnabled = optimizer.isInImprovementMode;
  90367. return true;
  90368. };
  90369. ;
  90370. return ParticlesOptimization;
  90371. }(SceneOptimization));
  90372. BABYLON.ParticlesOptimization = ParticlesOptimization;
  90373. /**
  90374. * Defines an optimization used to turn render targets off
  90375. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90376. */
  90377. var RenderTargetsOptimization = /** @class */ (function (_super) {
  90378. __extends(RenderTargetsOptimization, _super);
  90379. function RenderTargetsOptimization() {
  90380. return _super !== null && _super.apply(this, arguments) || this;
  90381. }
  90382. /**
  90383. * Gets a string describing the action executed by the current optimization
  90384. * @return description string
  90385. */
  90386. RenderTargetsOptimization.prototype.getDescription = function () {
  90387. return "Turning render targets off";
  90388. };
  90389. /**
  90390. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90391. * @param scene defines the current scene where to apply this optimization
  90392. * @param optimizer defines the current optimizer
  90393. * @returns true if everything that can be done was applied
  90394. */
  90395. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  90396. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  90397. return true;
  90398. };
  90399. ;
  90400. return RenderTargetsOptimization;
  90401. }(SceneOptimization));
  90402. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  90403. /**
  90404. * Defines an optimization used to merge meshes with compatible materials
  90405. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90406. */
  90407. var MergeMeshesOptimization = /** @class */ (function (_super) {
  90408. __extends(MergeMeshesOptimization, _super);
  90409. function MergeMeshesOptimization() {
  90410. var _this = _super !== null && _super.apply(this, arguments) || this;
  90411. _this._canBeMerged = function (abstractMesh) {
  90412. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  90413. return false;
  90414. }
  90415. var mesh = abstractMesh;
  90416. if (!mesh.isVisible || !mesh.isEnabled()) {
  90417. return false;
  90418. }
  90419. if (mesh.instances.length > 0) {
  90420. return false;
  90421. }
  90422. if (mesh.skeleton || mesh.hasLODLevels) {
  90423. return false;
  90424. }
  90425. if (mesh.parent) {
  90426. return false;
  90427. }
  90428. return true;
  90429. };
  90430. return _this;
  90431. }
  90432. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  90433. /**
  90434. * Gets or sets a boolean which defines if optimization octree has to be updated
  90435. */
  90436. get: function () {
  90437. return MergeMeshesOptimization._UpdateSelectionTree;
  90438. },
  90439. /**
  90440. * Gets or sets a boolean which defines if optimization octree has to be updated
  90441. */
  90442. set: function (value) {
  90443. MergeMeshesOptimization._UpdateSelectionTree = value;
  90444. },
  90445. enumerable: true,
  90446. configurable: true
  90447. });
  90448. /**
  90449. * Gets a string describing the action executed by the current optimization
  90450. * @return description string
  90451. */
  90452. MergeMeshesOptimization.prototype.getDescription = function () {
  90453. return "Merging similar meshes together";
  90454. };
  90455. /**
  90456. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90457. * @param scene defines the current scene where to apply this optimization
  90458. * @param optimizer defines the current optimizer
  90459. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  90460. * @returns true if everything that can be done was applied
  90461. */
  90462. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  90463. var globalPool = scene.meshes.slice(0);
  90464. var globalLength = globalPool.length;
  90465. for (var index = 0; index < globalLength; index++) {
  90466. var currentPool = new Array();
  90467. var current = globalPool[index];
  90468. // Checks
  90469. if (!this._canBeMerged(current)) {
  90470. continue;
  90471. }
  90472. currentPool.push(current);
  90473. // Find compatible meshes
  90474. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  90475. var otherMesh = globalPool[subIndex];
  90476. if (!this._canBeMerged(otherMesh)) {
  90477. continue;
  90478. }
  90479. if (otherMesh.material !== current.material) {
  90480. continue;
  90481. }
  90482. if (otherMesh.checkCollisions !== current.checkCollisions) {
  90483. continue;
  90484. }
  90485. currentPool.push(otherMesh);
  90486. globalLength--;
  90487. globalPool.splice(subIndex, 1);
  90488. subIndex--;
  90489. }
  90490. if (currentPool.length < 2) {
  90491. continue;
  90492. }
  90493. // Merge meshes
  90494. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  90495. }
  90496. if (updateSelectionTree != undefined) {
  90497. if (updateSelectionTree) {
  90498. scene.createOrUpdateSelectionOctree();
  90499. }
  90500. }
  90501. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  90502. scene.createOrUpdateSelectionOctree();
  90503. }
  90504. return true;
  90505. };
  90506. ;
  90507. MergeMeshesOptimization._UpdateSelectionTree = false;
  90508. return MergeMeshesOptimization;
  90509. }(SceneOptimization));
  90510. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  90511. /**
  90512. * Defines a list of options used by SceneOptimizer
  90513. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90514. */
  90515. var SceneOptimizerOptions = /** @class */ (function () {
  90516. /**
  90517. * Creates a new list of options used by SceneOptimizer
  90518. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  90519. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  90520. */
  90521. function SceneOptimizerOptions(
  90522. /**
  90523. * Defines the target frame rate to reach (60 by default)
  90524. */
  90525. targetFrameRate,
  90526. /**
  90527. * Defines the interval between two checkes (2000ms by default)
  90528. */
  90529. trackerDuration) {
  90530. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  90531. if (trackerDuration === void 0) { trackerDuration = 2000; }
  90532. this.targetFrameRate = targetFrameRate;
  90533. this.trackerDuration = trackerDuration;
  90534. /**
  90535. * Gets the list of optimizations to apply
  90536. */
  90537. this.optimizations = new Array();
  90538. }
  90539. /**
  90540. * Add a new optimization
  90541. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  90542. * @returns the current SceneOptimizerOptions
  90543. */
  90544. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  90545. this.optimizations.push(optimization);
  90546. return this;
  90547. };
  90548. /**
  90549. * Add a new custom optimization
  90550. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  90551. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  90552. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90553. * @returns the current SceneOptimizerOptions
  90554. */
  90555. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  90556. if (priority === void 0) { priority = 0; }
  90557. var optimization = new CustomOptimization(priority);
  90558. optimization.onApply = onApply;
  90559. optimization.onGetDescription = onGetDescription;
  90560. this.optimizations.push(optimization);
  90561. return this;
  90562. };
  90563. /**
  90564. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  90565. * @param targetFrameRate defines the target frame rate (60 by default)
  90566. * @returns a SceneOptimizerOptions object
  90567. */
  90568. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  90569. var result = new SceneOptimizerOptions(targetFrameRate);
  90570. var priority = 0;
  90571. result.addOptimization(new MergeMeshesOptimization(priority));
  90572. result.addOptimization(new ShadowsOptimization(priority));
  90573. result.addOptimization(new LensFlaresOptimization(priority));
  90574. // Next priority
  90575. priority++;
  90576. result.addOptimization(new PostProcessesOptimization(priority));
  90577. result.addOptimization(new ParticlesOptimization(priority));
  90578. // Next priority
  90579. priority++;
  90580. result.addOptimization(new TextureOptimization(priority, 1024));
  90581. return result;
  90582. };
  90583. /**
  90584. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  90585. * @param targetFrameRate defines the target frame rate (60 by default)
  90586. * @returns a SceneOptimizerOptions object
  90587. */
  90588. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  90589. var result = new SceneOptimizerOptions(targetFrameRate);
  90590. var priority = 0;
  90591. result.addOptimization(new MergeMeshesOptimization(priority));
  90592. result.addOptimization(new ShadowsOptimization(priority));
  90593. result.addOptimization(new LensFlaresOptimization(priority));
  90594. // Next priority
  90595. priority++;
  90596. result.addOptimization(new PostProcessesOptimization(priority));
  90597. result.addOptimization(new ParticlesOptimization(priority));
  90598. // Next priority
  90599. priority++;
  90600. result.addOptimization(new TextureOptimization(priority, 512));
  90601. // Next priority
  90602. priority++;
  90603. result.addOptimization(new RenderTargetsOptimization(priority));
  90604. // Next priority
  90605. priority++;
  90606. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  90607. return result;
  90608. };
  90609. /**
  90610. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  90611. * @param targetFrameRate defines the target frame rate (60 by default)
  90612. * @returns a SceneOptimizerOptions object
  90613. */
  90614. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  90615. var result = new SceneOptimizerOptions(targetFrameRate);
  90616. var priority = 0;
  90617. result.addOptimization(new MergeMeshesOptimization(priority));
  90618. result.addOptimization(new ShadowsOptimization(priority));
  90619. result.addOptimization(new LensFlaresOptimization(priority));
  90620. // Next priority
  90621. priority++;
  90622. result.addOptimization(new PostProcessesOptimization(priority));
  90623. result.addOptimization(new ParticlesOptimization(priority));
  90624. // Next priority
  90625. priority++;
  90626. result.addOptimization(new TextureOptimization(priority, 256));
  90627. // Next priority
  90628. priority++;
  90629. result.addOptimization(new RenderTargetsOptimization(priority));
  90630. // Next priority
  90631. priority++;
  90632. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  90633. return result;
  90634. };
  90635. return SceneOptimizerOptions;
  90636. }());
  90637. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  90638. /**
  90639. * Class used to run optimizations in order to reach a target frame rate
  90640. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90641. */
  90642. var SceneOptimizer = /** @class */ (function () {
  90643. /**
  90644. * Creates a new SceneOptimizer
  90645. * @param scene defines the scene to work on
  90646. * @param options defines the options to use with the SceneOptimizer
  90647. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  90648. * @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)
  90649. */
  90650. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  90651. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  90652. if (improvementMode === void 0) { improvementMode = false; }
  90653. var _this = this;
  90654. this._isRunning = false;
  90655. this._currentPriorityLevel = 0;
  90656. this._targetFrameRate = 60;
  90657. this._trackerDuration = 2000;
  90658. this._currentFrameRate = 0;
  90659. this._improvementMode = false;
  90660. /**
  90661. * Defines an observable called when the optimizer reaches the target frame rate
  90662. */
  90663. this.onSuccessObservable = new BABYLON.Observable();
  90664. /**
  90665. * Defines an observable called when the optimizer enables an optimization
  90666. */
  90667. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  90668. /**
  90669. * Defines an observable called when the optimizer is not able to reach the target frame rate
  90670. */
  90671. this.onFailureObservable = new BABYLON.Observable();
  90672. if (!options) {
  90673. this._options = new SceneOptimizerOptions();
  90674. }
  90675. else {
  90676. this._options = options;
  90677. }
  90678. if (this._options.targetFrameRate) {
  90679. this._targetFrameRate = this._options.targetFrameRate;
  90680. }
  90681. if (this._options.trackerDuration) {
  90682. this._trackerDuration = this._options.trackerDuration;
  90683. }
  90684. if (autoGeneratePriorities) {
  90685. var priority = 0;
  90686. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  90687. var optim = _a[_i];
  90688. optim.priority = priority++;
  90689. }
  90690. }
  90691. this._improvementMode = improvementMode;
  90692. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90693. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  90694. _this._sceneDisposeObserver = null;
  90695. _this.dispose();
  90696. });
  90697. }
  90698. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  90699. /**
  90700. * Gets a boolean indicating if the optimizer is in improvement mode
  90701. */
  90702. get: function () {
  90703. return this._improvementMode;
  90704. },
  90705. enumerable: true,
  90706. configurable: true
  90707. });
  90708. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  90709. /**
  90710. * Gets the current priority level (0 at start)
  90711. */
  90712. get: function () {
  90713. return this._currentPriorityLevel;
  90714. },
  90715. enumerable: true,
  90716. configurable: true
  90717. });
  90718. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  90719. /**
  90720. * Gets the current frame rate checked by the SceneOptimizer
  90721. */
  90722. get: function () {
  90723. return this._currentFrameRate;
  90724. },
  90725. enumerable: true,
  90726. configurable: true
  90727. });
  90728. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  90729. /**
  90730. * Gets or sets the current target frame rate (60 by default)
  90731. */
  90732. get: function () {
  90733. return this._targetFrameRate;
  90734. },
  90735. /**
  90736. * Gets or sets the current target frame rate (60 by default)
  90737. */
  90738. set: function (value) {
  90739. this._targetFrameRate = value;
  90740. },
  90741. enumerable: true,
  90742. configurable: true
  90743. });
  90744. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  90745. /**
  90746. * Gets or sets the current interval between two checks (every 2000ms by default)
  90747. */
  90748. get: function () {
  90749. return this._trackerDuration;
  90750. },
  90751. /**
  90752. * Gets or sets the current interval between two checks (every 2000ms by default)
  90753. */
  90754. set: function (value) {
  90755. this._trackerDuration = value;
  90756. },
  90757. enumerable: true,
  90758. configurable: true
  90759. });
  90760. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90761. /**
  90762. * Gets the list of active optimizations
  90763. */
  90764. get: function () {
  90765. return this._options.optimizations;
  90766. },
  90767. enumerable: true,
  90768. configurable: true
  90769. });
  90770. /**
  90771. * Stops the current optimizer
  90772. */
  90773. SceneOptimizer.prototype.stop = function () {
  90774. this._isRunning = false;
  90775. };
  90776. /**
  90777. * Reset the optimizer to initial step (current priority level = 0)
  90778. */
  90779. SceneOptimizer.prototype.reset = function () {
  90780. this._currentPriorityLevel = 0;
  90781. };
  90782. /**
  90783. * Start the optimizer. By default it will try to reach a specific framerate
  90784. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  90785. */
  90786. SceneOptimizer.prototype.start = function () {
  90787. var _this = this;
  90788. if (this._isRunning) {
  90789. return;
  90790. }
  90791. this._isRunning = true;
  90792. // Let's wait for the scene to be ready before running our check
  90793. this._scene.executeWhenReady(function () {
  90794. setTimeout(function () {
  90795. _this._checkCurrentState();
  90796. }, _this._trackerDuration);
  90797. });
  90798. };
  90799. SceneOptimizer.prototype._checkCurrentState = function () {
  90800. var _this = this;
  90801. if (!this._isRunning) {
  90802. return;
  90803. }
  90804. var scene = this._scene;
  90805. var options = this._options;
  90806. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  90807. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  90808. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  90809. this._isRunning = false;
  90810. this.onSuccessObservable.notifyObservers(this);
  90811. return;
  90812. }
  90813. // Apply current level of optimizations
  90814. var allDone = true;
  90815. var noOptimizationApplied = true;
  90816. for (var index = 0; index < options.optimizations.length; index++) {
  90817. var optimization = options.optimizations[index];
  90818. if (optimization.priority === this._currentPriorityLevel) {
  90819. noOptimizationApplied = false;
  90820. allDone = allDone && optimization.apply(scene, this);
  90821. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  90822. }
  90823. }
  90824. // If no optimization was applied, this is a failure :(
  90825. if (noOptimizationApplied) {
  90826. this._isRunning = false;
  90827. this.onFailureObservable.notifyObservers(this);
  90828. return;
  90829. }
  90830. // If all optimizations were done, move to next level
  90831. if (allDone) {
  90832. this._currentPriorityLevel++;
  90833. }
  90834. // Let's the system running for a specific amount of time before checking FPS
  90835. scene.executeWhenReady(function () {
  90836. setTimeout(function () {
  90837. _this._checkCurrentState();
  90838. }, _this._trackerDuration);
  90839. });
  90840. };
  90841. /**
  90842. * Release all resources
  90843. */
  90844. SceneOptimizer.prototype.dispose = function () {
  90845. this.stop();
  90846. this.onSuccessObservable.clear();
  90847. this.onFailureObservable.clear();
  90848. this.onNewOptimizationAppliedObservable.clear();
  90849. if (this._sceneDisposeObserver) {
  90850. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90851. }
  90852. };
  90853. /**
  90854. * Helper function to create a SceneOptimizer with one single line of code
  90855. * @param scene defines the scene to work on
  90856. * @param options defines the options to use with the SceneOptimizer
  90857. * @param onSuccess defines a callback to call on success
  90858. * @param onFailure defines a callback to call on failure
  90859. * @returns the new SceneOptimizer object
  90860. */
  90861. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  90862. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  90863. if (onSuccess) {
  90864. optimizer.onSuccessObservable.add(function () {
  90865. onSuccess();
  90866. });
  90867. }
  90868. if (onFailure) {
  90869. optimizer.onFailureObservable.add(function () {
  90870. onFailure();
  90871. });
  90872. }
  90873. optimizer.start();
  90874. return optimizer;
  90875. };
  90876. return SceneOptimizer;
  90877. }());
  90878. BABYLON.SceneOptimizer = SceneOptimizer;
  90879. })(BABYLON || (BABYLON = {}));
  90880. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  90881. var BABYLON;
  90882. (function (BABYLON) {
  90883. var OutlineRenderer = /** @class */ (function () {
  90884. function OutlineRenderer(scene) {
  90885. this.zOffset = 1;
  90886. this._scene = scene;
  90887. }
  90888. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  90889. var _this = this;
  90890. if (useOverlay === void 0) { useOverlay = false; }
  90891. var scene = this._scene;
  90892. var engine = this._scene.getEngine();
  90893. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90894. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  90895. return;
  90896. }
  90897. var mesh = subMesh.getRenderingMesh();
  90898. var material = subMesh.getMaterial();
  90899. if (!material || !scene.activeCamera) {
  90900. return;
  90901. }
  90902. engine.enableEffect(this._effect);
  90903. // Logarithmic depth
  90904. if (material.useLogarithmicDepth) {
  90905. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  90906. }
  90907. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  90908. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  90909. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  90910. // Bones
  90911. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90912. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90913. }
  90914. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  90915. // Alpha test
  90916. if (material && material.needAlphaTesting()) {
  90917. var alphaTexture = material.getAlphaTestTexture();
  90918. if (alphaTexture) {
  90919. this._effect.setTexture("diffuseSampler", alphaTexture);
  90920. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90921. }
  90922. }
  90923. engine.setZOffset(-this.zOffset);
  90924. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  90925. engine.setZOffset(0);
  90926. };
  90927. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  90928. var defines = [];
  90929. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90930. var mesh = subMesh.getMesh();
  90931. var material = subMesh.getMaterial();
  90932. if (material) {
  90933. // Alpha test
  90934. if (material.needAlphaTesting()) {
  90935. defines.push("#define ALPHATEST");
  90936. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90937. attribs.push(BABYLON.VertexBuffer.UVKind);
  90938. defines.push("#define UV1");
  90939. }
  90940. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90941. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90942. defines.push("#define UV2");
  90943. }
  90944. }
  90945. //Logarithmic depth
  90946. if (material.useLogarithmicDepth) {
  90947. defines.push("#define LOGARITHMICDEPTH");
  90948. }
  90949. }
  90950. // Bones
  90951. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90952. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90953. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90954. if (mesh.numBoneInfluencers > 4) {
  90955. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90956. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90957. }
  90958. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90959. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  90960. }
  90961. else {
  90962. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90963. }
  90964. // Instances
  90965. if (useInstances) {
  90966. defines.push("#define INSTANCES");
  90967. attribs.push("world0");
  90968. attribs.push("world1");
  90969. attribs.push("world2");
  90970. attribs.push("world3");
  90971. }
  90972. // Get correct effect
  90973. var join = defines.join("\n");
  90974. if (this._cachedDefines !== join) {
  90975. this._cachedDefines = join;
  90976. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  90977. }
  90978. return this._effect.isReady();
  90979. };
  90980. return OutlineRenderer;
  90981. }());
  90982. BABYLON.OutlineRenderer = OutlineRenderer;
  90983. })(BABYLON || (BABYLON = {}));
  90984. //# sourceMappingURL=babylon.outlineRenderer.js.map
  90985. var BABYLON;
  90986. (function (BABYLON) {
  90987. var FaceAdjacencies = /** @class */ (function () {
  90988. function FaceAdjacencies() {
  90989. this.edges = new Array();
  90990. this.edgesConnectedCount = 0;
  90991. }
  90992. return FaceAdjacencies;
  90993. }());
  90994. var EdgesRenderer = /** @class */ (function () {
  90995. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  90996. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  90997. if (epsilon === void 0) { epsilon = 0.95; }
  90998. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  90999. this.edgesWidthScalerForOrthographic = 1000.0;
  91000. this.edgesWidthScalerForPerspective = 50.0;
  91001. this._linesPositions = new Array();
  91002. this._linesNormals = new Array();
  91003. this._linesIndices = new Array();
  91004. this._buffers = {};
  91005. this._checkVerticesInsteadOfIndices = false;
  91006. this._source = source;
  91007. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  91008. this._epsilon = epsilon;
  91009. this._prepareRessources();
  91010. this._generateEdgesLines();
  91011. }
  91012. EdgesRenderer.prototype._prepareRessources = function () {
  91013. if (this._lineShader) {
  91014. return;
  91015. }
  91016. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  91017. attributes: ["position", "normal"],
  91018. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  91019. });
  91020. this._lineShader.disableDepthWrite = true;
  91021. this._lineShader.backFaceCulling = false;
  91022. };
  91023. EdgesRenderer.prototype._rebuild = function () {
  91024. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91025. if (buffer) {
  91026. buffer._rebuild();
  91027. }
  91028. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91029. if (buffer) {
  91030. buffer._rebuild();
  91031. }
  91032. var scene = this._source.getScene();
  91033. var engine = scene.getEngine();
  91034. this._ib = engine.createIndexBuffer(this._linesIndices);
  91035. };
  91036. EdgesRenderer.prototype.dispose = function () {
  91037. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91038. if (buffer) {
  91039. buffer.dispose();
  91040. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  91041. }
  91042. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91043. if (buffer) {
  91044. buffer.dispose();
  91045. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  91046. }
  91047. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  91048. this._lineShader.dispose();
  91049. };
  91050. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  91051. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  91052. return 0;
  91053. }
  91054. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  91055. return 1;
  91056. }
  91057. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  91058. return 2;
  91059. }
  91060. return -1;
  91061. };
  91062. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  91063. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  91064. return 0;
  91065. }
  91066. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  91067. return 1;
  91068. }
  91069. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  91070. return 2;
  91071. }
  91072. return -1;
  91073. };
  91074. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  91075. var needToCreateLine;
  91076. if (edge === undefined) {
  91077. needToCreateLine = true;
  91078. }
  91079. else {
  91080. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  91081. needToCreateLine = dotProduct < this._epsilon;
  91082. }
  91083. if (needToCreateLine) {
  91084. var offset = this._linesPositions.length / 3;
  91085. var normal = p0.subtract(p1);
  91086. normal.normalize();
  91087. // Positions
  91088. this._linesPositions.push(p0.x);
  91089. this._linesPositions.push(p0.y);
  91090. this._linesPositions.push(p0.z);
  91091. this._linesPositions.push(p0.x);
  91092. this._linesPositions.push(p0.y);
  91093. this._linesPositions.push(p0.z);
  91094. this._linesPositions.push(p1.x);
  91095. this._linesPositions.push(p1.y);
  91096. this._linesPositions.push(p1.z);
  91097. this._linesPositions.push(p1.x);
  91098. this._linesPositions.push(p1.y);
  91099. this._linesPositions.push(p1.z);
  91100. // Normals
  91101. this._linesNormals.push(p1.x);
  91102. this._linesNormals.push(p1.y);
  91103. this._linesNormals.push(p1.z);
  91104. this._linesNormals.push(-1);
  91105. this._linesNormals.push(p1.x);
  91106. this._linesNormals.push(p1.y);
  91107. this._linesNormals.push(p1.z);
  91108. this._linesNormals.push(1);
  91109. this._linesNormals.push(p0.x);
  91110. this._linesNormals.push(p0.y);
  91111. this._linesNormals.push(p0.z);
  91112. this._linesNormals.push(-1);
  91113. this._linesNormals.push(p0.x);
  91114. this._linesNormals.push(p0.y);
  91115. this._linesNormals.push(p0.z);
  91116. this._linesNormals.push(1);
  91117. // Indices
  91118. this._linesIndices.push(offset);
  91119. this._linesIndices.push(offset + 1);
  91120. this._linesIndices.push(offset + 2);
  91121. this._linesIndices.push(offset);
  91122. this._linesIndices.push(offset + 2);
  91123. this._linesIndices.push(offset + 3);
  91124. }
  91125. };
  91126. EdgesRenderer.prototype._generateEdgesLines = function () {
  91127. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91128. var indices = this._source.getIndices();
  91129. if (!indices || !positions) {
  91130. return;
  91131. }
  91132. // First let's find adjacencies
  91133. var adjacencies = new Array();
  91134. var faceNormals = new Array();
  91135. var index;
  91136. var faceAdjacencies;
  91137. // Prepare faces
  91138. for (index = 0; index < indices.length; index += 3) {
  91139. faceAdjacencies = new FaceAdjacencies();
  91140. var p0Index = indices[index];
  91141. var p1Index = indices[index + 1];
  91142. var p2Index = indices[index + 2];
  91143. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91144. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91145. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91146. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91147. faceNormal.normalize();
  91148. faceNormals.push(faceNormal);
  91149. adjacencies.push(faceAdjacencies);
  91150. }
  91151. // Scan
  91152. for (index = 0; index < adjacencies.length; index++) {
  91153. faceAdjacencies = adjacencies[index];
  91154. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91155. var otherFaceAdjacencies = adjacencies[otherIndex];
  91156. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91157. break;
  91158. }
  91159. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91160. continue;
  91161. }
  91162. var otherP0 = indices[otherIndex * 3];
  91163. var otherP1 = indices[otherIndex * 3 + 1];
  91164. var otherP2 = indices[otherIndex * 3 + 2];
  91165. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  91166. var otherEdgeIndex = 0;
  91167. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  91168. continue;
  91169. }
  91170. switch (edgeIndex) {
  91171. case 0:
  91172. if (this._checkVerticesInsteadOfIndices) {
  91173. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91174. }
  91175. else {
  91176. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  91177. }
  91178. break;
  91179. case 1:
  91180. if (this._checkVerticesInsteadOfIndices) {
  91181. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91182. }
  91183. else {
  91184. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91185. }
  91186. break;
  91187. case 2:
  91188. if (this._checkVerticesInsteadOfIndices) {
  91189. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91190. }
  91191. else {
  91192. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91193. }
  91194. break;
  91195. }
  91196. if (otherEdgeIndex === -1) {
  91197. continue;
  91198. }
  91199. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91200. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91201. faceAdjacencies.edgesConnectedCount++;
  91202. otherFaceAdjacencies.edgesConnectedCount++;
  91203. if (faceAdjacencies.edgesConnectedCount === 3) {
  91204. break;
  91205. }
  91206. }
  91207. }
  91208. }
  91209. // Create lines
  91210. for (index = 0; index < adjacencies.length; index++) {
  91211. // 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
  91212. var current = adjacencies[index];
  91213. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91214. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91215. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91216. }
  91217. // Merge into a single mesh
  91218. var engine = this._source.getScene().getEngine();
  91219. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91220. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91221. this._ib = engine.createIndexBuffer(this._linesIndices);
  91222. this._indicesCount = this._linesIndices.length;
  91223. };
  91224. EdgesRenderer.prototype.render = function () {
  91225. var scene = this._source.getScene();
  91226. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91227. return;
  91228. }
  91229. var engine = scene.getEngine();
  91230. this._lineShader._preBind();
  91231. // VBOs
  91232. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91233. scene.resetCachedMaterial();
  91234. this._lineShader.setColor4("color", this._source.edgesColor);
  91235. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91236. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91237. }
  91238. else {
  91239. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91240. }
  91241. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91242. this._lineShader.bind(this._source.getWorldMatrix());
  91243. // Draw order
  91244. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91245. this._lineShader.unbind();
  91246. engine.setDepthWrite(true);
  91247. };
  91248. return EdgesRenderer;
  91249. }());
  91250. BABYLON.EdgesRenderer = EdgesRenderer;
  91251. })(BABYLON || (BABYLON = {}));
  91252. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91253. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91254. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91255. s = arguments[i];
  91256. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91257. t[p] = s[p];
  91258. }
  91259. return t;
  91260. };
  91261. var BABYLON;
  91262. (function (BABYLON) {
  91263. /**
  91264. * The effect layer Helps adding post process effect blended with the main pass.
  91265. *
  91266. * This can be for instance use to generate glow or higlight effects on the scene.
  91267. *
  91268. * The effect layer class can not be used directly and is intented to inherited from to be
  91269. * customized per effects.
  91270. */
  91271. var EffectLayer = /** @class */ (function () {
  91272. /**
  91273. * Instantiates a new effect Layer and references it in the scene.
  91274. * @param name The name of the layer
  91275. * @param scene The scene to use the layer in
  91276. */
  91277. function EffectLayer(
  91278. /** The Friendly of the effect in the scene */
  91279. name, scene) {
  91280. this._vertexBuffers = {};
  91281. this._maxSize = 0;
  91282. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91283. this._shouldRender = true;
  91284. this._postProcesses = [];
  91285. this._textures = [];
  91286. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91287. /**
  91288. * The clear color of the texture used to generate the glow map.
  91289. */
  91290. this.neutralColor = new BABYLON.Color4();
  91291. /**
  91292. * Specifies wether the highlight layer is enabled or not.
  91293. */
  91294. this.isEnabled = true;
  91295. /**
  91296. * An event triggered when the effect layer has been disposed.
  91297. */
  91298. this.onDisposeObservable = new BABYLON.Observable();
  91299. /**
  91300. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91301. */
  91302. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91303. /**
  91304. * An event triggered when the generated texture is being merged in the scene.
  91305. */
  91306. this.onBeforeComposeObservable = new BABYLON.Observable();
  91307. /**
  91308. * An event triggered when the generated texture has been merged in the scene.
  91309. */
  91310. this.onAfterComposeObservable = new BABYLON.Observable();
  91311. /**
  91312. * An event triggered when the efffect layer changes its size.
  91313. */
  91314. this.onSizeChangedObservable = new BABYLON.Observable();
  91315. this.name = name;
  91316. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91317. this._engine = scene.getEngine();
  91318. this._maxSize = this._engine.getCaps().maxTextureSize;
  91319. this._scene.effectLayers.push(this);
  91320. // Generate Buffers
  91321. this._generateIndexBuffer();
  91322. this._genrateVertexBuffer();
  91323. }
  91324. Object.defineProperty(EffectLayer.prototype, "camera", {
  91325. /**
  91326. * Gets the camera attached to the layer.
  91327. */
  91328. get: function () {
  91329. return this._effectLayerOptions.camera;
  91330. },
  91331. enumerable: true,
  91332. configurable: true
  91333. });
  91334. /**
  91335. * Initializes the effect layer with the required options.
  91336. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  91337. */
  91338. EffectLayer.prototype._init = function (options) {
  91339. // Adapt options
  91340. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91341. this._setMainTextureSize();
  91342. this._createMainTexture();
  91343. this._createTextureAndPostProcesses();
  91344. this._mergeEffect = this._createMergeEffect();
  91345. };
  91346. /**
  91347. * Generates the index buffer of the full screen quad blending to the main canvas.
  91348. */
  91349. EffectLayer.prototype._generateIndexBuffer = function () {
  91350. // Indices
  91351. var indices = [];
  91352. indices.push(0);
  91353. indices.push(1);
  91354. indices.push(2);
  91355. indices.push(0);
  91356. indices.push(2);
  91357. indices.push(3);
  91358. this._indexBuffer = this._engine.createIndexBuffer(indices);
  91359. };
  91360. /**
  91361. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  91362. */
  91363. EffectLayer.prototype._genrateVertexBuffer = function () {
  91364. // VBO
  91365. var vertices = [];
  91366. vertices.push(1, 1);
  91367. vertices.push(-1, 1);
  91368. vertices.push(-1, -1);
  91369. vertices.push(1, -1);
  91370. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91371. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91372. };
  91373. /**
  91374. * Sets the main texture desired size which is the closest power of two
  91375. * of the engine canvas size.
  91376. */
  91377. EffectLayer.prototype._setMainTextureSize = function () {
  91378. if (this._effectLayerOptions.mainTextureFixedSize) {
  91379. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  91380. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  91381. }
  91382. else {
  91383. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  91384. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  91385. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  91386. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  91387. }
  91388. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  91389. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  91390. };
  91391. /**
  91392. * Creates the main texture for the effect layer.
  91393. */
  91394. EffectLayer.prototype._createMainTexture = function () {
  91395. var _this = this;
  91396. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  91397. width: this._mainTextureDesiredSize.width,
  91398. height: this._mainTextureDesiredSize.height
  91399. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91400. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  91401. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91402. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91403. this._mainTexture.anisotropicFilteringLevel = 1;
  91404. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91405. this._mainTexture.renderParticles = false;
  91406. this._mainTexture.renderList = null;
  91407. this._mainTexture.ignoreCameraViewport = true;
  91408. // Custom render function
  91409. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91410. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  91411. var index;
  91412. var engine = _this._scene.getEngine();
  91413. if (depthOnlySubMeshes.length) {
  91414. engine.setColorWrite(false);
  91415. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91416. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  91417. }
  91418. engine.setColorWrite(true);
  91419. }
  91420. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91421. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  91422. }
  91423. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91424. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  91425. }
  91426. for (index = 0; index < transparentSubMeshes.length; index++) {
  91427. _this._renderSubMesh(transparentSubMeshes.data[index]);
  91428. }
  91429. };
  91430. this._mainTexture.onClearObservable.add(function (engine) {
  91431. engine.clear(_this.neutralColor, true, true, true);
  91432. });
  91433. };
  91434. /**
  91435. * Checks for the readiness of the element composing the layer.
  91436. * @param subMesh the mesh to check for
  91437. * @param useInstances specify wether or not to use instances to render the mesh
  91438. * @param emissiveTexture the associated emissive texture used to generate the glow
  91439. * @return true if ready otherwise, false
  91440. */
  91441. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  91442. var material = subMesh.getMaterial();
  91443. if (!material) {
  91444. return false;
  91445. }
  91446. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  91447. return false;
  91448. }
  91449. var defines = [];
  91450. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91451. var mesh = subMesh.getMesh();
  91452. var uv1 = false;
  91453. var uv2 = false;
  91454. // Alpha test
  91455. if (material && material.needAlphaTesting()) {
  91456. var alphaTexture = material.getAlphaTestTexture();
  91457. if (alphaTexture) {
  91458. defines.push("#define ALPHATEST");
  91459. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91460. alphaTexture.coordinatesIndex === 1) {
  91461. defines.push("#define DIFFUSEUV2");
  91462. uv2 = true;
  91463. }
  91464. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91465. defines.push("#define DIFFUSEUV1");
  91466. uv1 = true;
  91467. }
  91468. }
  91469. }
  91470. // Emissive
  91471. if (emissiveTexture) {
  91472. defines.push("#define EMISSIVE");
  91473. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91474. emissiveTexture.coordinatesIndex === 1) {
  91475. defines.push("#define EMISSIVEUV2");
  91476. uv2 = true;
  91477. }
  91478. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91479. defines.push("#define EMISSIVEUV1");
  91480. uv1 = true;
  91481. }
  91482. }
  91483. if (uv1) {
  91484. attribs.push(BABYLON.VertexBuffer.UVKind);
  91485. defines.push("#define UV1");
  91486. }
  91487. if (uv2) {
  91488. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91489. defines.push("#define UV2");
  91490. }
  91491. // Bones
  91492. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91493. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91494. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91495. if (mesh.numBoneInfluencers > 4) {
  91496. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91497. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91498. }
  91499. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91500. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  91501. }
  91502. else {
  91503. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91504. }
  91505. // Morph targets
  91506. var manager = mesh.morphTargetManager;
  91507. var morphInfluencers = 0;
  91508. if (manager) {
  91509. if (manager.numInfluencers > 0) {
  91510. defines.push("#define MORPHTARGETS");
  91511. morphInfluencers = manager.numInfluencers;
  91512. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  91513. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  91514. }
  91515. }
  91516. // Instances
  91517. if (useInstances) {
  91518. defines.push("#define INSTANCES");
  91519. attribs.push("world0");
  91520. attribs.push("world1");
  91521. attribs.push("world2");
  91522. attribs.push("world3");
  91523. }
  91524. // Get correct effect
  91525. var join = defines.join("\n");
  91526. if (this._cachedDefines !== join) {
  91527. this._cachedDefines = join;
  91528. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  91529. }
  91530. return this._effectLayerMapGenerationEffect.isReady();
  91531. };
  91532. /**
  91533. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  91534. */
  91535. EffectLayer.prototype.render = function () {
  91536. var currentEffect = this._mergeEffect;
  91537. // Check
  91538. if (!currentEffect.isReady())
  91539. return;
  91540. for (var i = 0; i < this._postProcesses.length; i++) {
  91541. if (!this._postProcesses[i].isReady()) {
  91542. return;
  91543. }
  91544. }
  91545. var engine = this._scene.getEngine();
  91546. this.onBeforeComposeObservable.notifyObservers(this);
  91547. // Render
  91548. engine.enableEffect(currentEffect);
  91549. engine.setState(false);
  91550. // VBOs
  91551. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91552. // Cache
  91553. var previousAlphaMode = engine.getAlphaMode();
  91554. // Go Blend.
  91555. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  91556. // Blends the map on the main canvas.
  91557. this._internalRender(currentEffect);
  91558. // Restore Alpha
  91559. engine.setAlphaMode(previousAlphaMode);
  91560. this.onAfterComposeObservable.notifyObservers(this);
  91561. // Handle size changes.
  91562. var size = this._mainTexture.getSize();
  91563. this._setMainTextureSize();
  91564. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  91565. // Recreate RTT and post processes on size change.
  91566. this.onSizeChangedObservable.notifyObservers(this);
  91567. this._disposeTextureAndPostProcesses();
  91568. this._createMainTexture();
  91569. this._createTextureAndPostProcesses();
  91570. }
  91571. };
  91572. /**
  91573. * Determine if a given mesh will be used in the current effect.
  91574. * @param mesh mesh to test
  91575. * @returns true if the mesh will be used
  91576. */
  91577. EffectLayer.prototype.hasMesh = function (mesh) {
  91578. return true;
  91579. };
  91580. /**
  91581. * Returns true if the layer contains information to display, otherwise false.
  91582. * @returns true if the glow layer should be rendered
  91583. */
  91584. EffectLayer.prototype.shouldRender = function () {
  91585. return this.isEnabled && this._shouldRender;
  91586. };
  91587. /**
  91588. * Returns true if the mesh should render, otherwise false.
  91589. * @param mesh The mesh to render
  91590. * @returns true if it should render otherwise false
  91591. */
  91592. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  91593. return true;
  91594. };
  91595. /**
  91596. * Returns true if the mesh should render, otherwise false.
  91597. * @param mesh The mesh to render
  91598. * @returns true if it should render otherwise false
  91599. */
  91600. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  91601. return true;
  91602. };
  91603. /**
  91604. * Renders the submesh passed in parameter to the generation map.
  91605. */
  91606. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  91607. var _this = this;
  91608. if (!this.shouldRender()) {
  91609. return;
  91610. }
  91611. var material = subMesh.getMaterial();
  91612. var mesh = subMesh.getRenderingMesh();
  91613. var scene = this._scene;
  91614. var engine = scene.getEngine();
  91615. if (!material) {
  91616. return;
  91617. }
  91618. // Do not block in blend mode.
  91619. if (material.needAlphaBlendingForMesh(mesh)) {
  91620. return;
  91621. }
  91622. // Culling
  91623. engine.setState(material.backFaceCulling);
  91624. // Managing instances
  91625. var batch = mesh._getInstancesRenderList(subMesh._id);
  91626. if (batch.mustReturn) {
  91627. return;
  91628. }
  91629. // Early Exit per mesh
  91630. if (!this._shouldRenderMesh(mesh)) {
  91631. return;
  91632. }
  91633. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91634. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  91635. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  91636. engine.enableEffect(this._effectLayerMapGenerationEffect);
  91637. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  91638. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  91639. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  91640. // Alpha test
  91641. if (material && material.needAlphaTesting()) {
  91642. var alphaTexture = material.getAlphaTestTexture();
  91643. if (alphaTexture) {
  91644. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  91645. var textureMatrix = alphaTexture.getTextureMatrix();
  91646. if (textureMatrix) {
  91647. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  91648. }
  91649. }
  91650. }
  91651. // Glow emissive only
  91652. if (this._emissiveTextureAndColor.texture) {
  91653. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  91654. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  91655. }
  91656. // Bones
  91657. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91658. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91659. }
  91660. // Morph targets
  91661. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  91662. // Draw
  91663. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  91664. }
  91665. else {
  91666. // Need to reset refresh rate of the shadowMap
  91667. this._mainTexture.resetRefreshCounter();
  91668. }
  91669. };
  91670. /**
  91671. * Rebuild the required buffers.
  91672. * @hidden Internal use only.
  91673. */
  91674. EffectLayer.prototype._rebuild = function () {
  91675. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91676. if (vb) {
  91677. vb._rebuild();
  91678. }
  91679. this._generateIndexBuffer();
  91680. };
  91681. /**
  91682. * Dispose only the render target textures and post process.
  91683. */
  91684. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  91685. this._mainTexture.dispose();
  91686. for (var i = 0; i < this._postProcesses.length; i++) {
  91687. if (this._postProcesses[i]) {
  91688. this._postProcesses[i].dispose();
  91689. }
  91690. }
  91691. this._postProcesses = [];
  91692. for (var i = 0; i < this._textures.length; i++) {
  91693. if (this._textures[i]) {
  91694. this._textures[i].dispose();
  91695. }
  91696. }
  91697. this._textures = [];
  91698. };
  91699. /**
  91700. * Dispose the highlight layer and free resources.
  91701. */
  91702. EffectLayer.prototype.dispose = function () {
  91703. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91704. if (vertexBuffer) {
  91705. vertexBuffer.dispose();
  91706. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91707. }
  91708. if (this._indexBuffer) {
  91709. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91710. this._indexBuffer = null;
  91711. }
  91712. // Clean textures and post processes
  91713. this._disposeTextureAndPostProcesses();
  91714. // Remove from scene
  91715. var index = this._scene.effectLayers.indexOf(this, 0);
  91716. if (index > -1) {
  91717. this._scene.effectLayers.splice(index, 1);
  91718. }
  91719. // Callback
  91720. this.onDisposeObservable.notifyObservers(this);
  91721. this.onDisposeObservable.clear();
  91722. this.onBeforeRenderMainTextureObservable.clear();
  91723. this.onBeforeComposeObservable.clear();
  91724. this.onAfterComposeObservable.clear();
  91725. this.onSizeChangedObservable.clear();
  91726. };
  91727. /**
  91728. * Gets the class name of the effect layer
  91729. * @returns the string with the class name of the effect layer
  91730. */
  91731. EffectLayer.prototype.getClassName = function () {
  91732. return "EffectLayer";
  91733. };
  91734. /**
  91735. * Creates an effect layer from parsed effect layer data
  91736. * @param parsedEffectLayer defines effect layer data
  91737. * @param scene defines the current scene
  91738. * @param rootUrl defines the root URL containing the effect layer information
  91739. * @returns a parsed effect Layer
  91740. */
  91741. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  91742. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  91743. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  91744. };
  91745. __decorate([
  91746. BABYLON.serialize()
  91747. ], EffectLayer.prototype, "name", void 0);
  91748. __decorate([
  91749. BABYLON.serializeAsColor4()
  91750. ], EffectLayer.prototype, "neutralColor", void 0);
  91751. __decorate([
  91752. BABYLON.serialize()
  91753. ], EffectLayer.prototype, "isEnabled", void 0);
  91754. __decorate([
  91755. BABYLON.serializeAsCameraReference()
  91756. ], EffectLayer.prototype, "camera", null);
  91757. return EffectLayer;
  91758. }());
  91759. BABYLON.EffectLayer = EffectLayer;
  91760. })(BABYLON || (BABYLON = {}));
  91761. //# sourceMappingURL=babylon.effectLayer.js.map
  91762. var BABYLON;
  91763. (function (BABYLON) {
  91764. /**
  91765. * Special Glow Blur post process only blurring the alpha channel
  91766. * It enforces keeping the most luminous color in the color channel.
  91767. */
  91768. var GlowBlurPostProcess = /** @class */ (function (_super) {
  91769. __extends(GlowBlurPostProcess, _super);
  91770. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  91771. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91772. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  91773. _this.direction = direction;
  91774. _this.kernel = kernel;
  91775. _this.onApplyObservable.add(function (effect) {
  91776. effect.setFloat2("screenSize", _this.width, _this.height);
  91777. effect.setVector2("direction", _this.direction);
  91778. effect.setFloat("blurWidth", _this.kernel);
  91779. });
  91780. return _this;
  91781. }
  91782. return GlowBlurPostProcess;
  91783. }(BABYLON.PostProcess));
  91784. /**
  91785. * The highlight layer Helps adding a glow effect around a mesh.
  91786. *
  91787. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91788. * glowy meshes to your scene.
  91789. *
  91790. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  91791. */
  91792. var HighlightLayer = /** @class */ (function (_super) {
  91793. __extends(HighlightLayer, _super);
  91794. /**
  91795. * Instantiates a new highlight Layer and references it to the scene..
  91796. * @param name The name of the layer
  91797. * @param scene The scene to use the layer in
  91798. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  91799. */
  91800. function HighlightLayer(name, scene, options) {
  91801. var _this = _super.call(this, name, scene) || this;
  91802. _this.name = name;
  91803. /**
  91804. * Specifies whether or not the inner glow is ACTIVE in the layer.
  91805. */
  91806. _this.innerGlow = true;
  91807. /**
  91808. * Specifies whether or not the outer glow is ACTIVE in the layer.
  91809. */
  91810. _this.outerGlow = true;
  91811. /**
  91812. * An event triggered when the highlight layer is being blurred.
  91813. */
  91814. _this.onBeforeBlurObservable = new BABYLON.Observable();
  91815. /**
  91816. * An event triggered when the highlight layer has been blurred.
  91817. */
  91818. _this.onAfterBlurObservable = new BABYLON.Observable();
  91819. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  91820. _this._meshes = {};
  91821. _this._excludedMeshes = {};
  91822. _this.neutralColor = HighlightLayer.NeutralColor;
  91823. // Warn on stencil
  91824. if (!_this._engine.isStencilEnable) {
  91825. 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 }");
  91826. }
  91827. // Adapt options
  91828. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91829. // Initialize the layer
  91830. _this._init({
  91831. alphaBlendingMode: _this._options.alphaBlendingMode,
  91832. camera: _this._options.camera,
  91833. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91834. mainTextureRatio: _this._options.mainTextureRatio
  91835. });
  91836. // Do not render as long as no meshes have been added
  91837. _this._shouldRender = false;
  91838. return _this;
  91839. }
  91840. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  91841. /**
  91842. * Gets the horizontal size of the blur.
  91843. */
  91844. get: function () {
  91845. return this._horizontalBlurPostprocess.kernel;
  91846. },
  91847. /**
  91848. * Specifies the horizontal size of the blur.
  91849. */
  91850. set: function (value) {
  91851. this._horizontalBlurPostprocess.kernel = value;
  91852. },
  91853. enumerable: true,
  91854. configurable: true
  91855. });
  91856. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  91857. /**
  91858. * Gets the vertical size of the blur.
  91859. */
  91860. get: function () {
  91861. return this._verticalBlurPostprocess.kernel;
  91862. },
  91863. /**
  91864. * Specifies the vertical size of the blur.
  91865. */
  91866. set: function (value) {
  91867. this._verticalBlurPostprocess.kernel = value;
  91868. },
  91869. enumerable: true,
  91870. configurable: true
  91871. });
  91872. /**
  91873. * Get the effect name of the layer.
  91874. * @return The effect name
  91875. */
  91876. HighlightLayer.prototype.getEffectName = function () {
  91877. return HighlightLayer.EffectName;
  91878. };
  91879. /**
  91880. * Create the merge effect. This is the shader use to blit the information back
  91881. * to the main canvas at the end of the scene rendering.
  91882. */
  91883. HighlightLayer.prototype._createMergeEffect = function () {
  91884. // Effect
  91885. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  91886. };
  91887. /**
  91888. * Creates the render target textures and post processes used in the highlight layer.
  91889. */
  91890. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  91891. var _this = this;
  91892. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  91893. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  91894. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91895. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91896. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  91897. width: blurTextureWidth,
  91898. height: blurTextureHeight
  91899. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91900. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91901. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91902. this._blurTexture.anisotropicFilteringLevel = 16;
  91903. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  91904. this._blurTexture.renderParticles = false;
  91905. this._blurTexture.ignoreCameraViewport = true;
  91906. this._textures = [this._blurTexture];
  91907. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  91908. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91909. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  91910. effect.setTexture("textureSampler", _this._mainTexture);
  91911. });
  91912. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91913. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91914. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91915. });
  91916. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91917. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  91918. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91919. });
  91920. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91921. }
  91922. else {
  91923. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  91924. width: blurTextureWidth,
  91925. height: blurTextureHeight
  91926. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91927. this._horizontalBlurPostprocess.width = blurTextureWidth;
  91928. this._horizontalBlurPostprocess.height = blurTextureHeight;
  91929. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91930. effect.setTexture("textureSampler", _this._mainTexture);
  91931. });
  91932. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  91933. width: blurTextureWidth,
  91934. height: blurTextureHeight
  91935. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91936. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91937. }
  91938. this._mainTexture.onAfterUnbindObservable.add(function () {
  91939. _this.onBeforeBlurObservable.notifyObservers(_this);
  91940. var internalTexture = _this._blurTexture.getInternalTexture();
  91941. if (internalTexture) {
  91942. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  91943. }
  91944. _this.onAfterBlurObservable.notifyObservers(_this);
  91945. });
  91946. // Prevent autoClear.
  91947. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91948. };
  91949. /**
  91950. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91951. */
  91952. HighlightLayer.prototype.needStencil = function () {
  91953. return true;
  91954. };
  91955. /**
  91956. * Checks for the readiness of the element composing the layer.
  91957. * @param subMesh the mesh to check for
  91958. * @param useInstances specify wether or not to use instances to render the mesh
  91959. * @param emissiveTexture the associated emissive texture used to generate the glow
  91960. * @return true if ready otherwise, false
  91961. */
  91962. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  91963. var material = subMesh.getMaterial();
  91964. var mesh = subMesh.getRenderingMesh();
  91965. if (!material || !mesh || !this._meshes) {
  91966. return false;
  91967. }
  91968. var emissiveTexture = null;
  91969. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91970. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91971. emissiveTexture = material.emissiveTexture;
  91972. }
  91973. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91974. };
  91975. /**
  91976. * Implementation specific of rendering the generating effect on the main canvas.
  91977. * @param effect The effect used to render through
  91978. */
  91979. HighlightLayer.prototype._internalRender = function (effect) {
  91980. // Texture
  91981. effect.setTexture("textureSampler", this._blurTexture);
  91982. // Cache
  91983. var engine = this._engine;
  91984. var previousStencilBuffer = engine.getStencilBuffer();
  91985. var previousStencilFunction = engine.getStencilFunction();
  91986. var previousStencilMask = engine.getStencilMask();
  91987. var previousStencilOperationPass = engine.getStencilOperationPass();
  91988. var previousStencilOperationFail = engine.getStencilOperationFail();
  91989. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  91990. var previousStencilReference = engine.getStencilFunctionReference();
  91991. // Stencil operations
  91992. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  91993. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  91994. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  91995. // Draw order
  91996. engine.setStencilMask(0x00);
  91997. engine.setStencilBuffer(true);
  91998. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  91999. // 2 passes inner outer
  92000. if (this.outerGlow) {
  92001. effect.setFloat("offset", 0);
  92002. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  92003. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92004. }
  92005. if (this.innerGlow) {
  92006. effect.setFloat("offset", 1);
  92007. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  92008. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92009. }
  92010. // Restore Cache
  92011. engine.setStencilFunction(previousStencilFunction);
  92012. engine.setStencilMask(previousStencilMask);
  92013. engine.setStencilBuffer(previousStencilBuffer);
  92014. engine.setStencilOperationPass(previousStencilOperationPass);
  92015. engine.setStencilOperationFail(previousStencilOperationFail);
  92016. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  92017. engine.setStencilFunctionReference(previousStencilReference);
  92018. };
  92019. /**
  92020. * Returns true if the layer contains information to display, otherwise false.
  92021. */
  92022. HighlightLayer.prototype.shouldRender = function () {
  92023. if (_super.prototype.shouldRender.call(this)) {
  92024. return this._meshes ? true : false;
  92025. }
  92026. return false;
  92027. };
  92028. /**
  92029. * Returns true if the mesh should render, otherwise false.
  92030. * @param mesh The mesh to render
  92031. * @returns true if it should render otherwise false
  92032. */
  92033. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  92034. // Excluded Mesh
  92035. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  92036. return false;
  92037. }
  92038. ;
  92039. return true;
  92040. };
  92041. /**
  92042. * Sets the required values for both the emissive texture and and the main color.
  92043. */
  92044. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92045. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92046. if (highlightLayerMesh) {
  92047. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  92048. }
  92049. else {
  92050. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92051. }
  92052. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92053. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92054. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  92055. }
  92056. else {
  92057. this._emissiveTextureAndColor.texture = null;
  92058. }
  92059. };
  92060. /**
  92061. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  92062. * @param mesh The mesh to exclude from the highlight layer
  92063. */
  92064. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  92065. if (!this._excludedMeshes) {
  92066. return;
  92067. }
  92068. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92069. if (!meshExcluded) {
  92070. this._excludedMeshes[mesh.uniqueId] = {
  92071. mesh: mesh,
  92072. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  92073. mesh.getEngine().setStencilBuffer(false);
  92074. }),
  92075. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  92076. mesh.getEngine().setStencilBuffer(true);
  92077. }),
  92078. };
  92079. }
  92080. };
  92081. /**
  92082. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  92083. * @param mesh The mesh to highlight
  92084. */
  92085. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  92086. if (!this._excludedMeshes) {
  92087. return;
  92088. }
  92089. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92090. if (meshExcluded) {
  92091. if (meshExcluded.beforeRender) {
  92092. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  92093. }
  92094. if (meshExcluded.afterRender) {
  92095. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  92096. }
  92097. }
  92098. this._excludedMeshes[mesh.uniqueId] = null;
  92099. };
  92100. /**
  92101. * Determine if a given mesh will be highlighted by the current HighlightLayer
  92102. * @param mesh mesh to test
  92103. * @returns true if the mesh will be highlighted by the current HighlightLayer
  92104. */
  92105. HighlightLayer.prototype.hasMesh = function (mesh) {
  92106. if (!this._meshes) {
  92107. return false;
  92108. }
  92109. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  92110. };
  92111. /**
  92112. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  92113. * @param mesh The mesh to highlight
  92114. * @param color The color of the highlight
  92115. * @param glowEmissiveOnly Extract the glow from the emissive texture
  92116. */
  92117. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  92118. var _this = this;
  92119. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  92120. if (!this._meshes) {
  92121. return;
  92122. }
  92123. var meshHighlight = this._meshes[mesh.uniqueId];
  92124. if (meshHighlight) {
  92125. meshHighlight.color = color;
  92126. }
  92127. else {
  92128. this._meshes[mesh.uniqueId] = {
  92129. mesh: mesh,
  92130. color: color,
  92131. // Lambda required for capture due to Observable this context
  92132. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92133. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92134. _this._defaultStencilReference(mesh);
  92135. }
  92136. else {
  92137. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92138. }
  92139. }),
  92140. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92141. glowEmissiveOnly: glowEmissiveOnly
  92142. };
  92143. }
  92144. this._shouldRender = true;
  92145. };
  92146. /**
  92147. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92148. * @param mesh The mesh to highlight
  92149. */
  92150. HighlightLayer.prototype.removeMesh = function (mesh) {
  92151. if (!this._meshes) {
  92152. return;
  92153. }
  92154. var meshHighlight = this._meshes[mesh.uniqueId];
  92155. if (meshHighlight) {
  92156. if (meshHighlight.observerHighlight) {
  92157. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92158. }
  92159. if (meshHighlight.observerDefault) {
  92160. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92161. }
  92162. delete this._meshes[mesh.uniqueId];
  92163. }
  92164. this._shouldRender = false;
  92165. for (var meshHighlightToCheck in this._meshes) {
  92166. if (this._meshes[meshHighlightToCheck]) {
  92167. this._shouldRender = true;
  92168. break;
  92169. }
  92170. }
  92171. };
  92172. /**
  92173. * Force the stencil to the normal expected value for none glowing parts
  92174. */
  92175. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  92176. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  92177. };
  92178. /**
  92179. * Free any resources and references associated to a mesh.
  92180. * Internal use
  92181. * @param mesh The mesh to free.
  92182. */
  92183. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92184. this.removeMesh(mesh);
  92185. this.removeExcludedMesh(mesh);
  92186. };
  92187. /**
  92188. * Dispose the highlight layer and free resources.
  92189. */
  92190. HighlightLayer.prototype.dispose = function () {
  92191. if (this._meshes) {
  92192. // Clean mesh references
  92193. for (var id in this._meshes) {
  92194. var meshHighlight = this._meshes[id];
  92195. if (meshHighlight && meshHighlight.mesh) {
  92196. if (meshHighlight.observerHighlight) {
  92197. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92198. }
  92199. if (meshHighlight.observerDefault) {
  92200. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92201. }
  92202. }
  92203. }
  92204. this._meshes = null;
  92205. }
  92206. if (this._excludedMeshes) {
  92207. for (var id in this._excludedMeshes) {
  92208. var meshHighlight = this._excludedMeshes[id];
  92209. if (meshHighlight) {
  92210. if (meshHighlight.beforeRender) {
  92211. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92212. }
  92213. if (meshHighlight.afterRender) {
  92214. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92215. }
  92216. }
  92217. }
  92218. this._excludedMeshes = null;
  92219. }
  92220. _super.prototype.dispose.call(this);
  92221. };
  92222. /**
  92223. * Gets the class name of the effect layer
  92224. * @returns the string with the class name of the effect layer
  92225. */
  92226. HighlightLayer.prototype.getClassName = function () {
  92227. return "HighlightLayer";
  92228. };
  92229. /**
  92230. * Serializes this Highlight layer
  92231. * @returns a serialized Highlight layer object
  92232. */
  92233. HighlightLayer.prototype.serialize = function () {
  92234. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92235. serializationObject.customType = "BABYLON.HighlightLayer";
  92236. // Highlighted meshes
  92237. serializationObject.meshes = [];
  92238. if (this._meshes) {
  92239. for (var m in this._meshes) {
  92240. var mesh = this._meshes[m];
  92241. if (mesh) {
  92242. serializationObject.meshes.push({
  92243. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92244. color: mesh.color.asArray(),
  92245. meshId: mesh.mesh.id
  92246. });
  92247. }
  92248. }
  92249. }
  92250. // Excluded meshes
  92251. serializationObject.excludedMeshes = [];
  92252. if (this._excludedMeshes) {
  92253. for (var e in this._excludedMeshes) {
  92254. var excludedMesh = this._excludedMeshes[e];
  92255. if (excludedMesh) {
  92256. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92257. }
  92258. }
  92259. }
  92260. return serializationObject;
  92261. };
  92262. /**
  92263. * Creates a Highlight layer from parsed Highlight layer data
  92264. * @param parsedHightlightLayer defines the Highlight layer data
  92265. * @param scene defines the current scene
  92266. * @param rootUrl defines the root URL containing the Highlight layer information
  92267. * @returns a parsed Highlight layer
  92268. */
  92269. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92270. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92271. var index;
  92272. // Excluded meshes
  92273. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92274. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92275. if (mesh) {
  92276. hl.addExcludedMesh(mesh);
  92277. }
  92278. }
  92279. // Included meshes
  92280. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92281. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92282. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92283. if (mesh) {
  92284. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92285. }
  92286. }
  92287. return hl;
  92288. };
  92289. /**
  92290. * Effect Name of the highlight layer.
  92291. */
  92292. HighlightLayer.EffectName = "HighlightLayer";
  92293. /**
  92294. * The neutral color used during the preparation of the glow effect.
  92295. * This is black by default as the blend operation is a blend operation.
  92296. */
  92297. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92298. /**
  92299. * Stencil value used for glowing meshes.
  92300. */
  92301. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92302. /**
  92303. * Stencil value used for the other meshes in the scene.
  92304. */
  92305. HighlightLayer.NormalMeshStencilReference = 0x01;
  92306. __decorate([
  92307. BABYLON.serialize()
  92308. ], HighlightLayer.prototype, "innerGlow", void 0);
  92309. __decorate([
  92310. BABYLON.serialize()
  92311. ], HighlightLayer.prototype, "outerGlow", void 0);
  92312. __decorate([
  92313. BABYLON.serialize()
  92314. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92315. __decorate([
  92316. BABYLON.serialize()
  92317. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92318. __decorate([
  92319. BABYLON.serialize("options")
  92320. ], HighlightLayer.prototype, "_options", void 0);
  92321. return HighlightLayer;
  92322. }(BABYLON.EffectLayer));
  92323. BABYLON.HighlightLayer = HighlightLayer;
  92324. })(BABYLON || (BABYLON = {}));
  92325. //# sourceMappingURL=babylon.highlightLayer.js.map
  92326. var BABYLON;
  92327. (function (BABYLON) {
  92328. /**
  92329. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92330. *
  92331. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92332. * glowy meshes to your scene.
  92333. *
  92334. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  92335. */
  92336. var GlowLayer = /** @class */ (function (_super) {
  92337. __extends(GlowLayer, _super);
  92338. /**
  92339. * Instantiates a new glow Layer and references it to the scene.
  92340. * @param name The name of the layer
  92341. * @param scene The scene to use the layer in
  92342. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  92343. */
  92344. function GlowLayer(name, scene, options) {
  92345. var _this = _super.call(this, name, scene) || this;
  92346. _this._intensity = 1.0;
  92347. _this._includedOnlyMeshes = [];
  92348. _this._excludedMeshes = [];
  92349. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  92350. // Adapt options
  92351. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  92352. // Initialize the layer
  92353. _this._init({
  92354. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  92355. camera: _this._options.camera,
  92356. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92357. mainTextureRatio: _this._options.mainTextureRatio
  92358. });
  92359. return _this;
  92360. }
  92361. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  92362. /**
  92363. * Gets the kernel size of the blur.
  92364. */
  92365. get: function () {
  92366. return this._horizontalBlurPostprocess1.kernel;
  92367. },
  92368. /**
  92369. * Sets the kernel size of the blur.
  92370. */
  92371. set: function (value) {
  92372. this._horizontalBlurPostprocess1.kernel = value;
  92373. this._verticalBlurPostprocess1.kernel = value;
  92374. this._horizontalBlurPostprocess2.kernel = value;
  92375. this._verticalBlurPostprocess2.kernel = value;
  92376. },
  92377. enumerable: true,
  92378. configurable: true
  92379. });
  92380. Object.defineProperty(GlowLayer.prototype, "intensity", {
  92381. /**
  92382. * Gets the glow intensity.
  92383. */
  92384. get: function () {
  92385. return this._intensity;
  92386. },
  92387. /**
  92388. * Sets the glow intensity.
  92389. */
  92390. set: function (value) {
  92391. this._intensity = value;
  92392. },
  92393. enumerable: true,
  92394. configurable: true
  92395. });
  92396. /**
  92397. * Get the effect name of the layer.
  92398. * @return The effect name
  92399. */
  92400. GlowLayer.prototype.getEffectName = function () {
  92401. return GlowLayer.EffectName;
  92402. };
  92403. /**
  92404. * Create the merge effect. This is the shader use to blit the information back
  92405. * to the main canvas at the end of the scene rendering.
  92406. */
  92407. GlowLayer.prototype._createMergeEffect = function () {
  92408. // Effect
  92409. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  92410. };
  92411. /**
  92412. * Creates the render target textures and post processes used in the glow layer.
  92413. */
  92414. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  92415. var _this = this;
  92416. var blurTextureWidth = this._mainTextureDesiredSize.width;
  92417. var blurTextureHeight = this._mainTextureDesiredSize.height;
  92418. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92419. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92420. var textureType = 0;
  92421. if (this._engine.getCaps().textureHalfFloatRender) {
  92422. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92423. }
  92424. else {
  92425. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92426. }
  92427. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  92428. width: blurTextureWidth,
  92429. height: blurTextureHeight
  92430. }, this._scene, false, true, textureType);
  92431. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92432. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92433. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92434. this._blurTexture1.renderParticles = false;
  92435. this._blurTexture1.ignoreCameraViewport = true;
  92436. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  92437. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  92438. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  92439. width: blurTextureWidth2,
  92440. height: blurTextureHeight2
  92441. }, this._scene, false, true, textureType);
  92442. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92443. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92444. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92445. this._blurTexture2.renderParticles = false;
  92446. this._blurTexture2.ignoreCameraViewport = true;
  92447. this._textures = [this._blurTexture1, this._blurTexture2];
  92448. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92449. width: blurTextureWidth,
  92450. height: blurTextureHeight
  92451. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92452. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  92453. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  92454. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  92455. effect.setTexture("textureSampler", _this._mainTexture);
  92456. });
  92457. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92458. width: blurTextureWidth,
  92459. height: blurTextureHeight
  92460. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92461. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92462. width: blurTextureWidth2,
  92463. height: blurTextureHeight2
  92464. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92465. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  92466. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  92467. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  92468. effect.setTexture("textureSampler", _this._blurTexture1);
  92469. });
  92470. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92471. width: blurTextureWidth2,
  92472. height: blurTextureHeight2
  92473. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92474. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92475. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  92476. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92477. this._mainTexture.samples = this._options.mainTextureSamples;
  92478. this._mainTexture.onAfterUnbindObservable.add(function () {
  92479. var internalTexture = _this._blurTexture1.getInternalTexture();
  92480. if (internalTexture) {
  92481. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  92482. internalTexture = _this._blurTexture2.getInternalTexture();
  92483. if (internalTexture) {
  92484. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  92485. }
  92486. }
  92487. });
  92488. // Prevent autoClear.
  92489. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92490. };
  92491. /**
  92492. * Checks for the readiness of the element composing the layer.
  92493. * @param subMesh the mesh to check for
  92494. * @param useInstances specify wether or not to use instances to render the mesh
  92495. * @param emissiveTexture the associated emissive texture used to generate the glow
  92496. * @return true if ready otherwise, false
  92497. */
  92498. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  92499. var material = subMesh.getMaterial();
  92500. var mesh = subMesh.getRenderingMesh();
  92501. if (!material || !mesh) {
  92502. return false;
  92503. }
  92504. var emissiveTexture = material.emissiveTexture;
  92505. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92506. };
  92507. /**
  92508. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92509. */
  92510. GlowLayer.prototype.needStencil = function () {
  92511. return false;
  92512. };
  92513. /**
  92514. * Implementation specific of rendering the generating effect on the main canvas.
  92515. * @param effect The effect used to render through
  92516. */
  92517. GlowLayer.prototype._internalRender = function (effect) {
  92518. // Texture
  92519. effect.setTexture("textureSampler", this._blurTexture1);
  92520. effect.setTexture("textureSampler2", this._blurTexture2);
  92521. effect.setFloat("offset", this._intensity);
  92522. // Cache
  92523. var engine = this._engine;
  92524. var previousStencilBuffer = engine.getStencilBuffer();
  92525. // Draw order
  92526. engine.setStencilBuffer(false);
  92527. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92528. // Draw order
  92529. engine.setStencilBuffer(previousStencilBuffer);
  92530. };
  92531. /**
  92532. * Sets the required values for both the emissive texture and and the main color.
  92533. */
  92534. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92535. var textureLevel = 1.0;
  92536. if (this.customEmissiveTextureSelector) {
  92537. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  92538. }
  92539. else {
  92540. if (material) {
  92541. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92542. if (this._emissiveTextureAndColor.texture) {
  92543. textureLevel = this._emissiveTextureAndColor.texture.level;
  92544. }
  92545. }
  92546. else {
  92547. this._emissiveTextureAndColor.texture = null;
  92548. }
  92549. }
  92550. if (this.customEmissiveColorSelector) {
  92551. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  92552. }
  92553. else {
  92554. if (material.emissiveColor) {
  92555. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  92556. }
  92557. else {
  92558. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92559. }
  92560. }
  92561. };
  92562. /**
  92563. * Returns true if the mesh should render, otherwise false.
  92564. * @param mesh The mesh to render
  92565. * @returns true if it should render otherwise false
  92566. */
  92567. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  92568. return this.hasMesh(mesh);
  92569. };
  92570. /**
  92571. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  92572. * @param mesh The mesh to exclude from the glow layer
  92573. */
  92574. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  92575. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  92576. this._excludedMeshes.push(mesh.uniqueId);
  92577. }
  92578. };
  92579. /**
  92580. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  92581. * @param mesh The mesh to remove
  92582. */
  92583. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  92584. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  92585. if (index !== -1) {
  92586. this._excludedMeshes.splice(index, 1);
  92587. }
  92588. };
  92589. /**
  92590. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  92591. * @param mesh The mesh to include in the glow layer
  92592. */
  92593. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  92594. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  92595. this._includedOnlyMeshes.push(mesh.uniqueId);
  92596. }
  92597. };
  92598. /**
  92599. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  92600. * @param mesh The mesh to remove
  92601. */
  92602. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  92603. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  92604. if (index !== -1) {
  92605. this._includedOnlyMeshes.splice(index, 1);
  92606. }
  92607. };
  92608. /**
  92609. * Determine if a given mesh will be used in the glow layer
  92610. * @param mesh The mesh to test
  92611. * @returns true if the mesh will be highlighted by the current glow layer
  92612. */
  92613. GlowLayer.prototype.hasMesh = function (mesh) {
  92614. // Included Mesh
  92615. if (this._includedOnlyMeshes.length) {
  92616. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  92617. }
  92618. ;
  92619. // Excluded Mesh
  92620. if (this._excludedMeshes.length) {
  92621. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  92622. }
  92623. ;
  92624. return true;
  92625. };
  92626. /**
  92627. * Free any resources and references associated to a mesh.
  92628. * Internal use
  92629. * @param mesh The mesh to free.
  92630. */
  92631. GlowLayer.prototype._disposeMesh = function (mesh) {
  92632. this.removeIncludedOnlyMesh(mesh);
  92633. this.removeExcludedMesh(mesh);
  92634. };
  92635. /**
  92636. * Gets the class name of the effect layer
  92637. * @returns the string with the class name of the effect layer
  92638. */
  92639. GlowLayer.prototype.getClassName = function () {
  92640. return "GlowLayer";
  92641. };
  92642. /**
  92643. * Serializes this glow layer
  92644. * @returns a serialized glow layer object
  92645. */
  92646. GlowLayer.prototype.serialize = function () {
  92647. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92648. serializationObject.customType = "BABYLON.GlowLayer";
  92649. var index;
  92650. // Included meshes
  92651. serializationObject.includedMeshes = [];
  92652. if (this._includedOnlyMeshes.length) {
  92653. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  92654. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  92655. if (mesh) {
  92656. serializationObject.includedMeshes.push(mesh.id);
  92657. }
  92658. }
  92659. }
  92660. // Excluded meshes
  92661. serializationObject.excludedMeshes = [];
  92662. if (this._excludedMeshes.length) {
  92663. for (index = 0; index < this._excludedMeshes.length; index++) {
  92664. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  92665. if (mesh) {
  92666. serializationObject.excludedMeshes.push(mesh.id);
  92667. }
  92668. }
  92669. }
  92670. return serializationObject;
  92671. };
  92672. /**
  92673. * Creates a Glow Layer from parsed glow layer data
  92674. * @param parsedGlowLayer defines glow layer data
  92675. * @param scene defines the current scene
  92676. * @param rootUrl defines the root URL containing the glow layer information
  92677. * @returns a parsed Glow Layer
  92678. */
  92679. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  92680. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  92681. var index;
  92682. // Excluded meshes
  92683. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  92684. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  92685. if (mesh) {
  92686. gl.addExcludedMesh(mesh);
  92687. }
  92688. }
  92689. // Included meshes
  92690. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  92691. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  92692. if (mesh) {
  92693. gl.addIncludedOnlyMesh(mesh);
  92694. }
  92695. }
  92696. return gl;
  92697. };
  92698. /**
  92699. * Effect Name of the layer.
  92700. */
  92701. GlowLayer.EffectName = "GlowLayer";
  92702. /**
  92703. * The default blur kernel size used for the glow.
  92704. */
  92705. GlowLayer.DefaultBlurKernelSize = 32;
  92706. /**
  92707. * The default texture size ratio used for the glow.
  92708. */
  92709. GlowLayer.DefaultTextureRatio = 0.5;
  92710. __decorate([
  92711. BABYLON.serialize()
  92712. ], GlowLayer.prototype, "blurKernelSize", null);
  92713. __decorate([
  92714. BABYLON.serialize()
  92715. ], GlowLayer.prototype, "intensity", null);
  92716. __decorate([
  92717. BABYLON.serialize("options")
  92718. ], GlowLayer.prototype, "_options", void 0);
  92719. return GlowLayer;
  92720. }(BABYLON.EffectLayer));
  92721. BABYLON.GlowLayer = GlowLayer;
  92722. })(BABYLON || (BABYLON = {}));
  92723. //# sourceMappingURL=babylon.glowLayer.js.map
  92724. var BABYLON;
  92725. (function (BABYLON) {
  92726. /**
  92727. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  92728. */
  92729. var AssetTaskState;
  92730. (function (AssetTaskState) {
  92731. /**
  92732. * Initialization
  92733. */
  92734. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  92735. /**
  92736. * Running
  92737. */
  92738. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  92739. /**
  92740. * Done
  92741. */
  92742. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  92743. /**
  92744. * Error
  92745. */
  92746. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  92747. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  92748. /**
  92749. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  92750. */
  92751. var AbstractAssetTask = /** @class */ (function () {
  92752. /**
  92753. * Creates a new {BABYLON.AssetsManager}
  92754. * @param name defines the name of the task
  92755. */
  92756. function AbstractAssetTask(
  92757. /**
  92758. * Task name
  92759. */ name) {
  92760. this.name = name;
  92761. this._isCompleted = false;
  92762. this._taskState = AssetTaskState.INIT;
  92763. }
  92764. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92765. /**
  92766. * Get if the task is completed
  92767. */
  92768. get: function () {
  92769. return this._isCompleted;
  92770. },
  92771. enumerable: true,
  92772. configurable: true
  92773. });
  92774. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  92775. /**
  92776. * Gets the current state of the task
  92777. */
  92778. get: function () {
  92779. return this._taskState;
  92780. },
  92781. enumerable: true,
  92782. configurable: true
  92783. });
  92784. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  92785. /**
  92786. * Gets the current error object (if task is in error)
  92787. */
  92788. get: function () {
  92789. return this._errorObject;
  92790. },
  92791. enumerable: true,
  92792. configurable: true
  92793. });
  92794. /**
  92795. * Internal only
  92796. * @hidden
  92797. */
  92798. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  92799. if (this._errorObject) {
  92800. return;
  92801. }
  92802. this._errorObject = {
  92803. message: message,
  92804. exception: exception
  92805. };
  92806. };
  92807. /**
  92808. * Execute the current task
  92809. * @param scene defines the scene where you want your assets to be loaded
  92810. * @param onSuccess is a callback called when the task is successfully executed
  92811. * @param onError is a callback called if an error occurs
  92812. */
  92813. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92814. var _this = this;
  92815. this._taskState = AssetTaskState.RUNNING;
  92816. this.runTask(scene, function () {
  92817. _this.onDoneCallback(onSuccess, onError);
  92818. }, function (msg, exception) {
  92819. _this.onErrorCallback(onError, msg, exception);
  92820. });
  92821. };
  92822. /**
  92823. * Execute the current task
  92824. * @param scene defines the scene where you want your assets to be loaded
  92825. * @param onSuccess is a callback called when the task is successfully executed
  92826. * @param onError is a callback called if an error occurs
  92827. */
  92828. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92829. throw new Error("runTask is not implemented");
  92830. };
  92831. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  92832. this._taskState = AssetTaskState.ERROR;
  92833. this._errorObject = {
  92834. message: message,
  92835. exception: exception
  92836. };
  92837. if (this.onError) {
  92838. this.onError(this, message, exception);
  92839. }
  92840. onError();
  92841. };
  92842. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  92843. try {
  92844. this._taskState = AssetTaskState.DONE;
  92845. this._isCompleted = true;
  92846. if (this.onSuccess) {
  92847. this.onSuccess(this);
  92848. }
  92849. onSuccess();
  92850. }
  92851. catch (e) {
  92852. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  92853. }
  92854. };
  92855. return AbstractAssetTask;
  92856. }());
  92857. BABYLON.AbstractAssetTask = AbstractAssetTask;
  92858. /**
  92859. * Class used to share progress information about assets loading
  92860. */
  92861. var AssetsProgressEvent = /** @class */ (function () {
  92862. /**
  92863. * Creates a {BABYLON.AssetsProgressEvent}
  92864. * @param remainingCount defines the number of remaining tasks to process
  92865. * @param totalCount defines the total number of tasks
  92866. * @param task defines the task that was just processed
  92867. */
  92868. function AssetsProgressEvent(remainingCount, totalCount, task) {
  92869. this.remainingCount = remainingCount;
  92870. this.totalCount = totalCount;
  92871. this.task = task;
  92872. }
  92873. return AssetsProgressEvent;
  92874. }());
  92875. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  92876. /**
  92877. * Define a task used by {BABYLON.AssetsManager} to load meshes
  92878. */
  92879. var MeshAssetTask = /** @class */ (function (_super) {
  92880. __extends(MeshAssetTask, _super);
  92881. /**
  92882. * Creates a new {BABYLON.MeshAssetTask}
  92883. * @param name defines the name of the task
  92884. * @param meshesNames defines the list of mesh's names you want to load
  92885. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  92886. * @param sceneFilename defines the filename of the scene to load from
  92887. */
  92888. function MeshAssetTask(
  92889. /**
  92890. * Defines the name of the task
  92891. */
  92892. name,
  92893. /**
  92894. * Defines the list of mesh's names you want to load
  92895. */
  92896. meshesNames,
  92897. /**
  92898. * Defines the root url to use as a base to load your meshes and associated resources
  92899. */
  92900. rootUrl,
  92901. /**
  92902. * Defines the filename of the scene to load from
  92903. */
  92904. sceneFilename) {
  92905. var _this = _super.call(this, name) || this;
  92906. _this.name = name;
  92907. _this.meshesNames = meshesNames;
  92908. _this.rootUrl = rootUrl;
  92909. _this.sceneFilename = sceneFilename;
  92910. return _this;
  92911. }
  92912. /**
  92913. * Execute the current task
  92914. * @param scene defines the scene where you want your assets to be loaded
  92915. * @param onSuccess is a callback called when the task is successfully executed
  92916. * @param onError is a callback called if an error occurs
  92917. */
  92918. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92919. var _this = this;
  92920. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  92921. _this.loadedMeshes = meshes;
  92922. _this.loadedParticleSystems = particleSystems;
  92923. _this.loadedSkeletons = skeletons;
  92924. onSuccess();
  92925. }, null, function (scene, message, exception) {
  92926. onError(message, exception);
  92927. });
  92928. };
  92929. return MeshAssetTask;
  92930. }(AbstractAssetTask));
  92931. BABYLON.MeshAssetTask = MeshAssetTask;
  92932. /**
  92933. * Define a task used by {BABYLON.AssetsManager} to load text content
  92934. */
  92935. var TextFileAssetTask = /** @class */ (function (_super) {
  92936. __extends(TextFileAssetTask, _super);
  92937. /**
  92938. * Creates a new TextFileAssetTask object
  92939. * @param name defines the name of the task
  92940. * @param url defines the location of the file to load
  92941. */
  92942. function TextFileAssetTask(
  92943. /**
  92944. * Defines the name of the task
  92945. */
  92946. name,
  92947. /**
  92948. * Defines the location of the file to load
  92949. */
  92950. url) {
  92951. var _this = _super.call(this, name) || this;
  92952. _this.name = name;
  92953. _this.url = url;
  92954. return _this;
  92955. }
  92956. /**
  92957. * Execute the current task
  92958. * @param scene defines the scene where you want your assets to be loaded
  92959. * @param onSuccess is a callback called when the task is successfully executed
  92960. * @param onError is a callback called if an error occurs
  92961. */
  92962. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92963. var _this = this;
  92964. scene._loadFile(this.url, function (data) {
  92965. _this.text = data;
  92966. onSuccess();
  92967. }, undefined, false, false, function (request, exception) {
  92968. if (request) {
  92969. onError(request.status + " " + request.statusText, exception);
  92970. }
  92971. });
  92972. };
  92973. return TextFileAssetTask;
  92974. }(AbstractAssetTask));
  92975. BABYLON.TextFileAssetTask = TextFileAssetTask;
  92976. /**
  92977. * Define a task used by {BABYLON.AssetsManager} to load binary data
  92978. */
  92979. var BinaryFileAssetTask = /** @class */ (function (_super) {
  92980. __extends(BinaryFileAssetTask, _super);
  92981. /**
  92982. * Creates a new BinaryFileAssetTask object
  92983. * @param name defines the name of the new task
  92984. * @param url defines the location of the file to load
  92985. */
  92986. function BinaryFileAssetTask(
  92987. /**
  92988. * Defines the name of the task
  92989. */
  92990. name,
  92991. /**
  92992. * Defines the location of the file to load
  92993. */
  92994. url) {
  92995. var _this = _super.call(this, name) || this;
  92996. _this.name = name;
  92997. _this.url = url;
  92998. return _this;
  92999. }
  93000. /**
  93001. * Execute the current task
  93002. * @param scene defines the scene where you want your assets to be loaded
  93003. * @param onSuccess is a callback called when the task is successfully executed
  93004. * @param onError is a callback called if an error occurs
  93005. */
  93006. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93007. var _this = this;
  93008. scene._loadFile(this.url, function (data) {
  93009. _this.data = data;
  93010. onSuccess();
  93011. }, undefined, true, true, function (request, exception) {
  93012. if (request) {
  93013. onError(request.status + " " + request.statusText, exception);
  93014. }
  93015. });
  93016. };
  93017. return BinaryFileAssetTask;
  93018. }(AbstractAssetTask));
  93019. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  93020. /**
  93021. * Define a task used by {BABYLON.AssetsManager} to load images
  93022. */
  93023. var ImageAssetTask = /** @class */ (function (_super) {
  93024. __extends(ImageAssetTask, _super);
  93025. /**
  93026. * Creates a new ImageAssetTask
  93027. * @param name defines the name of the task
  93028. * @param url defines the location of the image to load
  93029. */
  93030. function ImageAssetTask(
  93031. /**
  93032. * Defines the name of the task
  93033. */
  93034. name,
  93035. /**
  93036. * Defines the location of the image to load
  93037. */
  93038. url) {
  93039. var _this = _super.call(this, name) || this;
  93040. _this.name = name;
  93041. _this.url = url;
  93042. return _this;
  93043. }
  93044. /**
  93045. * Execute the current task
  93046. * @param scene defines the scene where you want your assets to be loaded
  93047. * @param onSuccess is a callback called when the task is successfully executed
  93048. * @param onError is a callback called if an error occurs
  93049. */
  93050. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93051. var _this = this;
  93052. var img = new Image();
  93053. BABYLON.Tools.SetCorsBehavior(this.url, img);
  93054. img.onload = function () {
  93055. _this.image = img;
  93056. onSuccess();
  93057. };
  93058. img.onerror = function (err) {
  93059. onError("Error loading image", err);
  93060. };
  93061. img.src = this.url;
  93062. };
  93063. return ImageAssetTask;
  93064. }(AbstractAssetTask));
  93065. BABYLON.ImageAssetTask = ImageAssetTask;
  93066. /**
  93067. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  93068. */
  93069. var TextureAssetTask = /** @class */ (function (_super) {
  93070. __extends(TextureAssetTask, _super);
  93071. /**
  93072. * Creates a new TextureAssetTask object
  93073. * @param name defines the name of the task
  93074. * @param url defines the location of the file to load
  93075. * @param noMipmap defines if mipmap should not be generated (default is false)
  93076. * @param invertY defines if texture must be inverted on Y axis (default is false)
  93077. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93078. */
  93079. function TextureAssetTask(
  93080. /**
  93081. * Defines the name of the task
  93082. */
  93083. name,
  93084. /**
  93085. * Defines the location of the file to load
  93086. */
  93087. url,
  93088. /**
  93089. * Defines if mipmap should not be generated (default is false)
  93090. */
  93091. noMipmap,
  93092. /**
  93093. * Defines if texture must be inverted on Y axis (default is false)
  93094. */
  93095. invertY,
  93096. /**
  93097. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93098. */
  93099. samplingMode) {
  93100. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93101. var _this = _super.call(this, name) || this;
  93102. _this.name = name;
  93103. _this.url = url;
  93104. _this.noMipmap = noMipmap;
  93105. _this.invertY = invertY;
  93106. _this.samplingMode = samplingMode;
  93107. return _this;
  93108. }
  93109. /**
  93110. * Execute the current task
  93111. * @param scene defines the scene where you want your assets to be loaded
  93112. * @param onSuccess is a callback called when the task is successfully executed
  93113. * @param onError is a callback called if an error occurs
  93114. */
  93115. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93116. var onload = function () {
  93117. onSuccess();
  93118. };
  93119. var onerror = function (message, exception) {
  93120. onError(message, exception);
  93121. };
  93122. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  93123. };
  93124. return TextureAssetTask;
  93125. }(AbstractAssetTask));
  93126. BABYLON.TextureAssetTask = TextureAssetTask;
  93127. /**
  93128. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  93129. */
  93130. var CubeTextureAssetTask = /** @class */ (function (_super) {
  93131. __extends(CubeTextureAssetTask, _super);
  93132. /**
  93133. * Creates a new CubeTextureAssetTask
  93134. * @param name defines the name of the task
  93135. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93136. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93137. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93138. * @param files defines the explicit list of files (undefined by default)
  93139. */
  93140. function CubeTextureAssetTask(
  93141. /**
  93142. * Defines the name of the task
  93143. */
  93144. name,
  93145. /**
  93146. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93147. */
  93148. url,
  93149. /**
  93150. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93151. */
  93152. extensions,
  93153. /**
  93154. * Defines if mipmaps should not be generated (default is false)
  93155. */
  93156. noMipmap,
  93157. /**
  93158. * Defines the explicit list of files (undefined by default)
  93159. */
  93160. files) {
  93161. var _this = _super.call(this, name) || this;
  93162. _this.name = name;
  93163. _this.url = url;
  93164. _this.extensions = extensions;
  93165. _this.noMipmap = noMipmap;
  93166. _this.files = files;
  93167. return _this;
  93168. }
  93169. /**
  93170. * Execute the current task
  93171. * @param scene defines the scene where you want your assets to be loaded
  93172. * @param onSuccess is a callback called when the task is successfully executed
  93173. * @param onError is a callback called if an error occurs
  93174. */
  93175. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93176. var onload = function () {
  93177. onSuccess();
  93178. };
  93179. var onerror = function (message, exception) {
  93180. onError(message, exception);
  93181. };
  93182. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93183. };
  93184. return CubeTextureAssetTask;
  93185. }(AbstractAssetTask));
  93186. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93187. /**
  93188. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93189. */
  93190. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93191. __extends(HDRCubeTextureAssetTask, _super);
  93192. /**
  93193. * Creates a new HDRCubeTextureAssetTask object
  93194. * @param name defines the name of the task
  93195. * @param url defines the location of the file to load
  93196. * @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.
  93197. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93198. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93199. * @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)
  93200. * @param reserved Internal use only
  93201. */
  93202. function HDRCubeTextureAssetTask(
  93203. /**
  93204. * Defines the name of the task
  93205. */
  93206. name,
  93207. /**
  93208. * Defines the location of the file to load
  93209. */
  93210. url,
  93211. /**
  93212. * Defines the desired size (the more it increases the longer the generation will be)
  93213. */
  93214. size,
  93215. /**
  93216. * Defines if mipmaps should not be generated (default is false)
  93217. */
  93218. noMipmap,
  93219. /**
  93220. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93221. */
  93222. generateHarmonics,
  93223. /**
  93224. * 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)
  93225. */
  93226. gammaSpace,
  93227. /**
  93228. * Internal Use Only
  93229. */
  93230. reserved) {
  93231. if (noMipmap === void 0) { noMipmap = false; }
  93232. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93233. if (gammaSpace === void 0) { gammaSpace = false; }
  93234. if (reserved === void 0) { reserved = false; }
  93235. var _this = _super.call(this, name) || this;
  93236. _this.name = name;
  93237. _this.url = url;
  93238. _this.size = size;
  93239. _this.noMipmap = noMipmap;
  93240. _this.generateHarmonics = generateHarmonics;
  93241. _this.gammaSpace = gammaSpace;
  93242. _this.reserved = reserved;
  93243. return _this;
  93244. }
  93245. /**
  93246. * Execute the current task
  93247. * @param scene defines the scene where you want your assets to be loaded
  93248. * @param onSuccess is a callback called when the task is successfully executed
  93249. * @param onError is a callback called if an error occurs
  93250. */
  93251. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93252. var onload = function () {
  93253. onSuccess();
  93254. };
  93255. var onerror = function (message, exception) {
  93256. onError(message, exception);
  93257. };
  93258. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  93259. };
  93260. return HDRCubeTextureAssetTask;
  93261. }(AbstractAssetTask));
  93262. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93263. /**
  93264. * This class can be used to easily import assets into a scene
  93265. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93266. */
  93267. var AssetsManager = /** @class */ (function () {
  93268. /**
  93269. * Creates a new AssetsManager
  93270. * @param scene defines the scene to work on
  93271. */
  93272. function AssetsManager(scene) {
  93273. this._isLoading = false;
  93274. this._tasks = new Array();
  93275. this._waitingTasksCount = 0;
  93276. this._totalTasksCount = 0;
  93277. /**
  93278. * Observable called when all tasks are processed
  93279. */
  93280. this.onTaskSuccessObservable = new BABYLON.Observable();
  93281. /**
  93282. * Observable called when a task had an error
  93283. */
  93284. this.onTaskErrorObservable = new BABYLON.Observable();
  93285. /**
  93286. * Observable called when a task is successful
  93287. */
  93288. this.onTasksDoneObservable = new BABYLON.Observable();
  93289. /**
  93290. * Observable called when a task is done (whatever the result is)
  93291. */
  93292. this.onProgressObservable = new BABYLON.Observable();
  93293. /**
  93294. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93295. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93296. */
  93297. this.useDefaultLoadingScreen = true;
  93298. this._scene = scene;
  93299. }
  93300. /**
  93301. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93302. * @param taskName defines the name of the new task
  93303. * @param meshesNames defines the name of meshes to load
  93304. * @param rootUrl defines the root url to use to locate files
  93305. * @param sceneFilename defines the filename of the scene file
  93306. * @returns a new {BABYLON.MeshAssetTask} object
  93307. */
  93308. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93309. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93310. this._tasks.push(task);
  93311. return task;
  93312. };
  93313. /**
  93314. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93315. * @param taskName defines the name of the new task
  93316. * @param url defines the url of the file to load
  93317. * @returns a new {BABYLON.TextFileAssetTask} object
  93318. */
  93319. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93320. var task = new TextFileAssetTask(taskName, url);
  93321. this._tasks.push(task);
  93322. return task;
  93323. };
  93324. /**
  93325. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93326. * @param taskName defines the name of the new task
  93327. * @param url defines the url of the file to load
  93328. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93329. */
  93330. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93331. var task = new BinaryFileAssetTask(taskName, url);
  93332. this._tasks.push(task);
  93333. return task;
  93334. };
  93335. /**
  93336. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  93337. * @param taskName defines the name of the new task
  93338. * @param url defines the url of the file to load
  93339. * @returns a new {BABYLON.ImageAssetTask} object
  93340. */
  93341. AssetsManager.prototype.addImageTask = function (taskName, url) {
  93342. var task = new ImageAssetTask(taskName, url);
  93343. this._tasks.push(task);
  93344. return task;
  93345. };
  93346. /**
  93347. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  93348. * @param taskName defines the name of the new task
  93349. * @param url defines the url of the file to load
  93350. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93351. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  93352. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  93353. * @returns a new {BABYLON.TextureAssetTask} object
  93354. */
  93355. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  93356. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93357. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  93358. this._tasks.push(task);
  93359. return task;
  93360. };
  93361. /**
  93362. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  93363. * @param taskName defines the name of the new task
  93364. * @param url defines the url of the file to load
  93365. * @param extensions defines the extension to use to load the cube map (can be null)
  93366. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93367. * @param files defines the list of files to load (can be null)
  93368. * @returns a new {BABYLON.CubeTextureAssetTask} object
  93369. */
  93370. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  93371. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  93372. this._tasks.push(task);
  93373. return task;
  93374. };
  93375. /**
  93376. *
  93377. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  93378. * @param taskName defines the name of the new task
  93379. * @param url defines the url of the file to load
  93380. * @param size defines the size you want for the cubemap (can be null)
  93381. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93382. * @param generateHarmonics defines if you want to automatically generate (true by default)
  93383. * @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)
  93384. * @param reserved Internal use only
  93385. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  93386. */
  93387. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  93388. if (noMipmap === void 0) { noMipmap = false; }
  93389. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93390. if (gammaSpace === void 0) { gammaSpace = false; }
  93391. if (reserved === void 0) { reserved = false; }
  93392. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  93393. this._tasks.push(task);
  93394. return task;
  93395. };
  93396. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  93397. var _this = this;
  93398. this._waitingTasksCount--;
  93399. try {
  93400. if (task.taskState === AssetTaskState.DONE) {
  93401. // Let's remove successfull tasks
  93402. BABYLON.Tools.SetImmediate(function () {
  93403. var index = _this._tasks.indexOf(task);
  93404. if (index > -1) {
  93405. _this._tasks.splice(index, 1);
  93406. }
  93407. });
  93408. }
  93409. if (this.onProgress) {
  93410. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  93411. }
  93412. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  93413. }
  93414. catch (e) {
  93415. BABYLON.Tools.Error("Error running progress callbacks.");
  93416. console.log(e);
  93417. }
  93418. if (this._waitingTasksCount === 0) {
  93419. try {
  93420. if (this.onFinish) {
  93421. this.onFinish(this._tasks);
  93422. }
  93423. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93424. }
  93425. catch (e) {
  93426. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  93427. console.log(e);
  93428. }
  93429. this._isLoading = false;
  93430. this._scene.getEngine().hideLoadingUI();
  93431. }
  93432. };
  93433. AssetsManager.prototype._runTask = function (task) {
  93434. var _this = this;
  93435. var done = function () {
  93436. try {
  93437. if (_this.onTaskSuccess) {
  93438. _this.onTaskSuccess(task);
  93439. }
  93440. _this.onTaskSuccessObservable.notifyObservers(task);
  93441. _this._decreaseWaitingTasksCount(task);
  93442. }
  93443. catch (e) {
  93444. error("Error executing task success callbacks", e);
  93445. }
  93446. };
  93447. var error = function (message, exception) {
  93448. task._setErrorObject(message, exception);
  93449. if (_this.onTaskError) {
  93450. _this.onTaskError(task);
  93451. }
  93452. _this.onTaskErrorObservable.notifyObservers(task);
  93453. _this._decreaseWaitingTasksCount(task);
  93454. };
  93455. task.run(this._scene, done, error);
  93456. };
  93457. /**
  93458. * Reset the {BABYLON.AssetsManager} and remove all tasks
  93459. * @return the current instance of the {BABYLON.AssetsManager}
  93460. */
  93461. AssetsManager.prototype.reset = function () {
  93462. this._isLoading = false;
  93463. this._tasks = new Array();
  93464. return this;
  93465. };
  93466. /**
  93467. * Start the loading process
  93468. * @return the current instance of the {BABYLON.AssetsManager}
  93469. */
  93470. AssetsManager.prototype.load = function () {
  93471. if (this._isLoading) {
  93472. return this;
  93473. }
  93474. this._isLoading = true;
  93475. this._waitingTasksCount = this._tasks.length;
  93476. this._totalTasksCount = this._tasks.length;
  93477. if (this._waitingTasksCount === 0) {
  93478. this._isLoading = false;
  93479. if (this.onFinish) {
  93480. this.onFinish(this._tasks);
  93481. }
  93482. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93483. return this;
  93484. }
  93485. if (this.useDefaultLoadingScreen) {
  93486. this._scene.getEngine().displayLoadingUI();
  93487. }
  93488. for (var index = 0; index < this._tasks.length; index++) {
  93489. var task = this._tasks[index];
  93490. this._runTask(task);
  93491. }
  93492. return this;
  93493. };
  93494. return AssetsManager;
  93495. }());
  93496. BABYLON.AssetsManager = AssetsManager;
  93497. })(BABYLON || (BABYLON = {}));
  93498. //# sourceMappingURL=babylon.assetsManager.js.map
  93499. var BABYLON;
  93500. (function (BABYLON) {
  93501. var serializedGeometries = [];
  93502. var serializeGeometry = function (geometry, serializationGeometries) {
  93503. if (serializedGeometries[geometry.id]) {
  93504. return;
  93505. }
  93506. if (geometry.doNotSerialize) {
  93507. return;
  93508. }
  93509. if (geometry instanceof BABYLON.BoxGeometry) {
  93510. serializationGeometries.boxes.push(geometry.serialize());
  93511. }
  93512. else if (geometry instanceof BABYLON.SphereGeometry) {
  93513. serializationGeometries.spheres.push(geometry.serialize());
  93514. }
  93515. else if (geometry instanceof BABYLON.CylinderGeometry) {
  93516. serializationGeometries.cylinders.push(geometry.serialize());
  93517. }
  93518. else if (geometry instanceof BABYLON.TorusGeometry) {
  93519. serializationGeometries.toruses.push(geometry.serialize());
  93520. }
  93521. else if (geometry instanceof BABYLON.GroundGeometry) {
  93522. serializationGeometries.grounds.push(geometry.serialize());
  93523. }
  93524. else if (geometry instanceof BABYLON.Plane) {
  93525. serializationGeometries.planes.push(geometry.serialize());
  93526. }
  93527. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  93528. serializationGeometries.torusKnots.push(geometry.serialize());
  93529. }
  93530. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  93531. throw new Error("Unknown primitive type");
  93532. }
  93533. else {
  93534. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  93535. }
  93536. serializedGeometries[geometry.id] = true;
  93537. };
  93538. var serializeMesh = function (mesh, serializationScene) {
  93539. var serializationObject = {};
  93540. // Geometry
  93541. var geometry = mesh._geometry;
  93542. if (geometry) {
  93543. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  93544. // 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
  93545. serializeGeometry(geometry, serializationScene.geometries);
  93546. }
  93547. }
  93548. // Custom
  93549. if (mesh.serialize) {
  93550. mesh.serialize(serializationObject);
  93551. }
  93552. return serializationObject;
  93553. };
  93554. var finalizeSingleMesh = function (mesh, serializationObject) {
  93555. //only works if the mesh is already loaded
  93556. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93557. //serialize material
  93558. if (mesh.material) {
  93559. if (mesh.material instanceof BABYLON.StandardMaterial) {
  93560. serializationObject.materials = serializationObject.materials || [];
  93561. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93562. serializationObject.materials.push(mesh.material.serialize());
  93563. }
  93564. }
  93565. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  93566. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  93567. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93568. serializationObject.multiMaterials.push(mesh.material.serialize());
  93569. }
  93570. }
  93571. }
  93572. //serialize geometry
  93573. var geometry = mesh._geometry;
  93574. if (geometry) {
  93575. if (!serializationObject.geometries) {
  93576. serializationObject.geometries = {};
  93577. serializationObject.geometries.boxes = [];
  93578. serializationObject.geometries.spheres = [];
  93579. serializationObject.geometries.cylinders = [];
  93580. serializationObject.geometries.toruses = [];
  93581. serializationObject.geometries.grounds = [];
  93582. serializationObject.geometries.planes = [];
  93583. serializationObject.geometries.torusKnots = [];
  93584. serializationObject.geometries.vertexData = [];
  93585. }
  93586. serializeGeometry(geometry, serializationObject.geometries);
  93587. }
  93588. // Skeletons
  93589. if (mesh.skeleton) {
  93590. serializationObject.skeletons = serializationObject.skeletons || [];
  93591. serializationObject.skeletons.push(mesh.skeleton.serialize());
  93592. }
  93593. //serialize the actual mesh
  93594. serializationObject.meshes = serializationObject.meshes || [];
  93595. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93596. }
  93597. };
  93598. var SceneSerializer = /** @class */ (function () {
  93599. function SceneSerializer() {
  93600. }
  93601. SceneSerializer.ClearCache = function () {
  93602. serializedGeometries = [];
  93603. };
  93604. SceneSerializer.Serialize = function (scene) {
  93605. var serializationObject = {};
  93606. SceneSerializer.ClearCache();
  93607. // Scene
  93608. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  93609. serializationObject.autoClear = scene.autoClear;
  93610. serializationObject.clearColor = scene.clearColor.asArray();
  93611. serializationObject.ambientColor = scene.ambientColor.asArray();
  93612. serializationObject.gravity = scene.gravity.asArray();
  93613. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  93614. serializationObject.workerCollisions = scene.workerCollisions;
  93615. // Fog
  93616. if (scene.fogMode && scene.fogMode !== 0) {
  93617. serializationObject.fogMode = scene.fogMode;
  93618. serializationObject.fogColor = scene.fogColor.asArray();
  93619. serializationObject.fogStart = scene.fogStart;
  93620. serializationObject.fogEnd = scene.fogEnd;
  93621. serializationObject.fogDensity = scene.fogDensity;
  93622. }
  93623. //Physics
  93624. if (scene.isPhysicsEnabled()) {
  93625. var physicEngine = scene.getPhysicsEngine();
  93626. if (physicEngine) {
  93627. serializationObject.physicsEnabled = true;
  93628. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  93629. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  93630. }
  93631. }
  93632. // Metadata
  93633. if (scene.metadata) {
  93634. serializationObject.metadata = scene.metadata;
  93635. }
  93636. // Morph targets
  93637. serializationObject.morphTargetManagers = [];
  93638. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  93639. var abstractMesh = _a[_i];
  93640. var manager = abstractMesh.morphTargetManager;
  93641. if (manager) {
  93642. serializationObject.morphTargetManagers.push(manager.serialize());
  93643. }
  93644. }
  93645. // Lights
  93646. serializationObject.lights = [];
  93647. var index;
  93648. var light;
  93649. for (index = 0; index < scene.lights.length; index++) {
  93650. light = scene.lights[index];
  93651. if (!light.doNotSerialize) {
  93652. serializationObject.lights.push(light.serialize());
  93653. }
  93654. }
  93655. // Cameras
  93656. serializationObject.cameras = [];
  93657. for (index = 0; index < scene.cameras.length; index++) {
  93658. var camera = scene.cameras[index];
  93659. if (!camera.doNotSerialize) {
  93660. serializationObject.cameras.push(camera.serialize());
  93661. }
  93662. }
  93663. if (scene.activeCamera) {
  93664. serializationObject.activeCameraID = scene.activeCamera.id;
  93665. }
  93666. // Animations
  93667. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  93668. // Materials
  93669. serializationObject.materials = [];
  93670. serializationObject.multiMaterials = [];
  93671. var material;
  93672. for (index = 0; index < scene.materials.length; index++) {
  93673. material = scene.materials[index];
  93674. if (!material.doNotSerialize) {
  93675. serializationObject.materials.push(material.serialize());
  93676. }
  93677. }
  93678. // MultiMaterials
  93679. serializationObject.multiMaterials = [];
  93680. for (index = 0; index < scene.multiMaterials.length; index++) {
  93681. var multiMaterial = scene.multiMaterials[index];
  93682. serializationObject.multiMaterials.push(multiMaterial.serialize());
  93683. }
  93684. // Environment texture
  93685. if (scene.environmentTexture) {
  93686. serializationObject.environmentTexture = scene.environmentTexture.name;
  93687. }
  93688. // Skeletons
  93689. serializationObject.skeletons = [];
  93690. for (index = 0; index < scene.skeletons.length; index++) {
  93691. var skeleton = scene.skeletons[index];
  93692. if (!skeleton.doNotSerialize) {
  93693. serializationObject.skeletons.push(skeleton.serialize());
  93694. }
  93695. }
  93696. // Transform nodes
  93697. serializationObject.transformNodes = [];
  93698. for (index = 0; index < scene.transformNodes.length; index++) {
  93699. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  93700. }
  93701. // Geometries
  93702. serializationObject.geometries = {};
  93703. serializationObject.geometries.boxes = [];
  93704. serializationObject.geometries.spheres = [];
  93705. serializationObject.geometries.cylinders = [];
  93706. serializationObject.geometries.toruses = [];
  93707. serializationObject.geometries.grounds = [];
  93708. serializationObject.geometries.planes = [];
  93709. serializationObject.geometries.torusKnots = [];
  93710. serializationObject.geometries.vertexData = [];
  93711. serializedGeometries = [];
  93712. var geometries = scene.getGeometries();
  93713. for (index = 0; index < geometries.length; index++) {
  93714. var geometry = geometries[index];
  93715. if (geometry.isReady()) {
  93716. serializeGeometry(geometry, serializationObject.geometries);
  93717. }
  93718. }
  93719. // Meshes
  93720. serializationObject.meshes = [];
  93721. for (index = 0; index < scene.meshes.length; index++) {
  93722. var abstractMesh = scene.meshes[index];
  93723. if (abstractMesh instanceof BABYLON.Mesh) {
  93724. var mesh = abstractMesh;
  93725. if (!mesh.doNotSerialize) {
  93726. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93727. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93728. }
  93729. }
  93730. }
  93731. }
  93732. // Particles Systems
  93733. serializationObject.particleSystems = [];
  93734. for (index = 0; index < scene.particleSystems.length; index++) {
  93735. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  93736. }
  93737. // Lens flares
  93738. serializationObject.lensFlareSystems = [];
  93739. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  93740. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  93741. }
  93742. // Shadows
  93743. serializationObject.shadowGenerators = [];
  93744. for (index = 0; index < scene.lights.length; index++) {
  93745. light = scene.lights[index];
  93746. var shadowGenerator = light.getShadowGenerator();
  93747. if (shadowGenerator) {
  93748. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  93749. }
  93750. }
  93751. // Action Manager
  93752. if (scene.actionManager) {
  93753. serializationObject.actions = scene.actionManager.serialize("scene");
  93754. }
  93755. // Audio
  93756. serializationObject.sounds = [];
  93757. for (index = 0; index < scene.soundTracks.length; index++) {
  93758. var soundtrack = scene.soundTracks[index];
  93759. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93760. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93761. }
  93762. }
  93763. // Effect layers
  93764. serializationObject.effectLayers = [];
  93765. for (index = 0; index < scene.effectLayers.length; index++) {
  93766. var layer = scene.effectLayers[index];
  93767. if (layer.serialize) {
  93768. serializationObject.effectLayers.push(layer.serialize());
  93769. }
  93770. }
  93771. return serializationObject;
  93772. };
  93773. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  93774. if (withParents === void 0) { withParents = false; }
  93775. if (withChildren === void 0) { withChildren = false; }
  93776. var serializationObject = {};
  93777. SceneSerializer.ClearCache();
  93778. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  93779. if (withParents || withChildren) {
  93780. //deliberate for loop! not for each, appended should be processed as well.
  93781. for (var i = 0; i < toSerialize.length; ++i) {
  93782. if (withChildren) {
  93783. toSerialize[i].getDescendants().forEach(function (node) {
  93784. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  93785. toSerialize.push(node);
  93786. }
  93787. });
  93788. }
  93789. //make sure the array doesn't contain the object already
  93790. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  93791. toSerialize.push(toSerialize[i].parent);
  93792. }
  93793. }
  93794. }
  93795. toSerialize.forEach(function (mesh) {
  93796. finalizeSingleMesh(mesh, serializationObject);
  93797. });
  93798. return serializationObject;
  93799. };
  93800. return SceneSerializer;
  93801. }());
  93802. BABYLON.SceneSerializer = SceneSerializer;
  93803. })(BABYLON || (BABYLON = {}));
  93804. //# sourceMappingURL=babylon.sceneSerializer.js.map
  93805. var BABYLON;
  93806. (function (BABYLON) {
  93807. var ReflectionProbe = /** @class */ (function () {
  93808. function ReflectionProbe(name, size, scene, generateMipMaps) {
  93809. if (generateMipMaps === void 0) { generateMipMaps = true; }
  93810. var _this = this;
  93811. this.name = name;
  93812. this._viewMatrix = BABYLON.Matrix.Identity();
  93813. this._target = BABYLON.Vector3.Zero();
  93814. this._add = BABYLON.Vector3.Zero();
  93815. this._invertYAxis = false;
  93816. this.position = BABYLON.Vector3.Zero();
  93817. this._scene = scene;
  93818. this._scene.reflectionProbes.push(this);
  93819. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  93820. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  93821. switch (faceIndex) {
  93822. case 0:
  93823. _this._add.copyFromFloats(1, 0, 0);
  93824. break;
  93825. case 1:
  93826. _this._add.copyFromFloats(-1, 0, 0);
  93827. break;
  93828. case 2:
  93829. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  93830. break;
  93831. case 3:
  93832. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  93833. break;
  93834. case 4:
  93835. _this._add.copyFromFloats(0, 0, 1);
  93836. break;
  93837. case 5:
  93838. _this._add.copyFromFloats(0, 0, -1);
  93839. break;
  93840. }
  93841. if (_this._attachedMesh) {
  93842. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  93843. }
  93844. _this.position.addToRef(_this._add, _this._target);
  93845. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  93846. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  93847. scene._forcedViewPosition = _this.position;
  93848. });
  93849. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  93850. scene._forcedViewPosition = null;
  93851. scene.updateTransformMatrix(true);
  93852. });
  93853. if (scene.activeCamera) {
  93854. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  93855. }
  93856. }
  93857. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  93858. get: function () {
  93859. return this._renderTargetTexture.samples;
  93860. },
  93861. set: function (value) {
  93862. this._renderTargetTexture.samples = value;
  93863. },
  93864. enumerable: true,
  93865. configurable: true
  93866. });
  93867. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  93868. get: function () {
  93869. return this._renderTargetTexture.refreshRate;
  93870. },
  93871. set: function (value) {
  93872. this._renderTargetTexture.refreshRate = value;
  93873. },
  93874. enumerable: true,
  93875. configurable: true
  93876. });
  93877. ReflectionProbe.prototype.getScene = function () {
  93878. return this._scene;
  93879. };
  93880. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  93881. get: function () {
  93882. return this._renderTargetTexture;
  93883. },
  93884. enumerable: true,
  93885. configurable: true
  93886. });
  93887. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  93888. get: function () {
  93889. return this._renderTargetTexture.renderList;
  93890. },
  93891. enumerable: true,
  93892. configurable: true
  93893. });
  93894. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  93895. this._attachedMesh = mesh;
  93896. };
  93897. /**
  93898. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  93899. *
  93900. * @param renderingGroupId The rendering group id corresponding to its index
  93901. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  93902. */
  93903. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  93904. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  93905. };
  93906. ReflectionProbe.prototype.dispose = function () {
  93907. var index = this._scene.reflectionProbes.indexOf(this);
  93908. if (index !== -1) {
  93909. // Remove from the scene if found
  93910. this._scene.reflectionProbes.splice(index, 1);
  93911. }
  93912. if (this._renderTargetTexture) {
  93913. this._renderTargetTexture.dispose();
  93914. this._renderTargetTexture = null;
  93915. }
  93916. };
  93917. return ReflectionProbe;
  93918. }());
  93919. BABYLON.ReflectionProbe = ReflectionProbe;
  93920. })(BABYLON || (BABYLON = {}));
  93921. //# sourceMappingURL=babylon.reflectionProbe.js.map
  93922. var BABYLON;
  93923. (function (BABYLON) {
  93924. var Layer = /** @class */ (function () {
  93925. function Layer(name, imgUrl, scene, isBackground, color) {
  93926. this.name = name;
  93927. this.scale = new BABYLON.Vector2(1, 1);
  93928. this.offset = new BABYLON.Vector2(0, 0);
  93929. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  93930. this.layerMask = 0x0FFFFFFF;
  93931. this._vertexBuffers = {};
  93932. // Events
  93933. /**
  93934. * An event triggered when the layer is disposed.
  93935. */
  93936. this.onDisposeObservable = new BABYLON.Observable();
  93937. /**
  93938. * An event triggered before rendering the scene
  93939. */
  93940. this.onBeforeRenderObservable = new BABYLON.Observable();
  93941. /**
  93942. * An event triggered after rendering the scene
  93943. */
  93944. this.onAfterRenderObservable = new BABYLON.Observable();
  93945. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  93946. this.isBackground = isBackground === undefined ? true : isBackground;
  93947. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  93948. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  93949. this._scene.layers.push(this);
  93950. var engine = this._scene.getEngine();
  93951. // VBO
  93952. var vertices = [];
  93953. vertices.push(1, 1);
  93954. vertices.push(-1, 1);
  93955. vertices.push(-1, -1);
  93956. vertices.push(1, -1);
  93957. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93958. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93959. this._createIndexBuffer();
  93960. // Effects
  93961. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  93962. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  93963. }
  93964. Object.defineProperty(Layer.prototype, "onDispose", {
  93965. set: function (callback) {
  93966. if (this._onDisposeObserver) {
  93967. this.onDisposeObservable.remove(this._onDisposeObserver);
  93968. }
  93969. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  93970. },
  93971. enumerable: true,
  93972. configurable: true
  93973. });
  93974. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  93975. set: function (callback) {
  93976. if (this._onBeforeRenderObserver) {
  93977. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  93978. }
  93979. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  93980. },
  93981. enumerable: true,
  93982. configurable: true
  93983. });
  93984. Object.defineProperty(Layer.prototype, "onAfterRender", {
  93985. set: function (callback) {
  93986. if (this._onAfterRenderObserver) {
  93987. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93988. }
  93989. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  93990. },
  93991. enumerable: true,
  93992. configurable: true
  93993. });
  93994. Layer.prototype._createIndexBuffer = function () {
  93995. var engine = this._scene.getEngine();
  93996. // Indices
  93997. var indices = [];
  93998. indices.push(0);
  93999. indices.push(1);
  94000. indices.push(2);
  94001. indices.push(0);
  94002. indices.push(2);
  94003. indices.push(3);
  94004. this._indexBuffer = engine.createIndexBuffer(indices);
  94005. };
  94006. Layer.prototype._rebuild = function () {
  94007. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94008. if (vb) {
  94009. vb._rebuild();
  94010. }
  94011. this._createIndexBuffer();
  94012. };
  94013. Layer.prototype.render = function () {
  94014. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  94015. // Check
  94016. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  94017. return;
  94018. var engine = this._scene.getEngine();
  94019. this.onBeforeRenderObservable.notifyObservers(this);
  94020. // Render
  94021. engine.enableEffect(currentEffect);
  94022. engine.setState(false);
  94023. // Texture
  94024. currentEffect.setTexture("textureSampler", this.texture);
  94025. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  94026. // Color
  94027. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  94028. // Scale / offset
  94029. currentEffect.setVector2("offset", this.offset);
  94030. currentEffect.setVector2("scale", this.scale);
  94031. // VBOs
  94032. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  94033. // Draw order
  94034. if (!this.alphaTest) {
  94035. engine.setAlphaMode(this.alphaBlendingMode);
  94036. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94037. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94038. }
  94039. else {
  94040. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94041. }
  94042. this.onAfterRenderObservable.notifyObservers(this);
  94043. };
  94044. Layer.prototype.dispose = function () {
  94045. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94046. if (vertexBuffer) {
  94047. vertexBuffer.dispose();
  94048. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94049. }
  94050. if (this._indexBuffer) {
  94051. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94052. this._indexBuffer = null;
  94053. }
  94054. if (this.texture) {
  94055. this.texture.dispose();
  94056. this.texture = null;
  94057. }
  94058. // Remove from scene
  94059. var index = this._scene.layers.indexOf(this);
  94060. this._scene.layers.splice(index, 1);
  94061. // Callback
  94062. this.onDisposeObservable.notifyObservers(this);
  94063. this.onDisposeObservable.clear();
  94064. this.onAfterRenderObservable.clear();
  94065. this.onBeforeRenderObservable.clear();
  94066. };
  94067. return Layer;
  94068. }());
  94069. BABYLON.Layer = Layer;
  94070. })(BABYLON || (BABYLON = {}));
  94071. //# sourceMappingURL=babylon.layer.js.map
  94072. var BABYLON;
  94073. (function (BABYLON) {
  94074. var TextureTools = /** @class */ (function () {
  94075. function TextureTools() {
  94076. }
  94077. /**
  94078. * Uses the GPU to create a copy texture rescaled at a given size
  94079. * @param texture Texture to copy from
  94080. * @param width Desired width
  94081. * @param height Desired height
  94082. * @return Generated texture
  94083. */
  94084. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  94085. if (useBilinearMode === void 0) { useBilinearMode = true; }
  94086. var scene = texture.getScene();
  94087. var engine = scene.getEngine();
  94088. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  94089. rtt.wrapU = texture.wrapU;
  94090. rtt.wrapV = texture.wrapV;
  94091. rtt.uOffset = texture.uOffset;
  94092. rtt.vOffset = texture.vOffset;
  94093. rtt.uScale = texture.uScale;
  94094. rtt.vScale = texture.vScale;
  94095. rtt.uAng = texture.uAng;
  94096. rtt.vAng = texture.vAng;
  94097. rtt.wAng = texture.wAng;
  94098. rtt.coordinatesIndex = texture.coordinatesIndex;
  94099. rtt.level = texture.level;
  94100. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  94101. rtt._texture.isReady = false;
  94102. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94103. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94104. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94105. passPostProcess.getEffect().executeWhenCompiled(function () {
  94106. passPostProcess.onApply = function (effect) {
  94107. effect.setTexture("textureSampler", texture);
  94108. };
  94109. var internalTexture = rtt.getInternalTexture();
  94110. if (internalTexture) {
  94111. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  94112. engine.unBindFramebuffer(internalTexture);
  94113. rtt.disposeFramebufferObjects();
  94114. passPostProcess.dispose();
  94115. internalTexture.isReady = true;
  94116. }
  94117. });
  94118. return rtt;
  94119. };
  94120. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  94121. if (!scene._environmentBRDFTexture) {
  94122. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94123. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94124. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94125. scene._environmentBRDFTexture = texture;
  94126. }
  94127. return scene._environmentBRDFTexture;
  94128. };
  94129. 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=";
  94130. return TextureTools;
  94131. }());
  94132. BABYLON.TextureTools = TextureTools;
  94133. })(BABYLON || (BABYLON = {}));
  94134. //# sourceMappingURL=babylon.textureTools.js.map
  94135. var BABYLON;
  94136. (function (BABYLON) {
  94137. var FramingBehavior = /** @class */ (function () {
  94138. function FramingBehavior() {
  94139. this._mode = FramingBehavior.FitFrustumSidesMode;
  94140. this._radiusScale = 1.0;
  94141. this._positionScale = 0.5;
  94142. this._defaultElevation = 0.3;
  94143. this._elevationReturnTime = 1500;
  94144. this._elevationReturnWaitTime = 1000;
  94145. this._zoomStopsAnimation = false;
  94146. this._framingTime = 1500;
  94147. this._isPointerDown = false;
  94148. this._lastInteractionTime = -Infinity;
  94149. // Framing control
  94150. this._animatables = new Array();
  94151. this._betaIsAnimating = false;
  94152. }
  94153. Object.defineProperty(FramingBehavior.prototype, "name", {
  94154. get: function () {
  94155. return "Framing";
  94156. },
  94157. enumerable: true,
  94158. configurable: true
  94159. });
  94160. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94161. /**
  94162. * Gets current mode used by the behavior.
  94163. */
  94164. get: function () {
  94165. return this._mode;
  94166. },
  94167. /**
  94168. * Sets the current mode used by the behavior
  94169. */
  94170. set: function (mode) {
  94171. this._mode = mode;
  94172. },
  94173. enumerable: true,
  94174. configurable: true
  94175. });
  94176. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  94177. /**
  94178. * Gets the scale applied to the radius
  94179. */
  94180. get: function () {
  94181. return this._radiusScale;
  94182. },
  94183. /**
  94184. * Sets the scale applied to the radius (1 by default)
  94185. */
  94186. set: function (radius) {
  94187. this._radiusScale = radius;
  94188. },
  94189. enumerable: true,
  94190. configurable: true
  94191. });
  94192. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94193. /**
  94194. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94195. */
  94196. get: function () {
  94197. return this._positionScale;
  94198. },
  94199. /**
  94200. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94201. */
  94202. set: function (scale) {
  94203. this._positionScale = scale;
  94204. },
  94205. enumerable: true,
  94206. configurable: true
  94207. });
  94208. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94209. /**
  94210. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94211. * behaviour is triggered, in radians.
  94212. */
  94213. get: function () {
  94214. return this._defaultElevation;
  94215. },
  94216. /**
  94217. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94218. * behaviour is triggered, in radians.
  94219. */
  94220. set: function (elevation) {
  94221. this._defaultElevation = elevation;
  94222. },
  94223. enumerable: true,
  94224. configurable: true
  94225. });
  94226. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94227. /**
  94228. * Gets the time (in milliseconds) taken to return to the default beta position.
  94229. * Negative value indicates camera should not return to default.
  94230. */
  94231. get: function () {
  94232. return this._elevationReturnTime;
  94233. },
  94234. /**
  94235. * Sets the time (in milliseconds) taken to return to the default beta position.
  94236. * Negative value indicates camera should not return to default.
  94237. */
  94238. set: function (speed) {
  94239. this._elevationReturnTime = speed;
  94240. },
  94241. enumerable: true,
  94242. configurable: true
  94243. });
  94244. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94245. /**
  94246. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94247. */
  94248. get: function () {
  94249. return this._elevationReturnWaitTime;
  94250. },
  94251. /**
  94252. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94253. */
  94254. set: function (time) {
  94255. this._elevationReturnWaitTime = time;
  94256. },
  94257. enumerable: true,
  94258. configurable: true
  94259. });
  94260. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94261. /**
  94262. * Gets the flag that indicates if user zooming should stop animation.
  94263. */
  94264. get: function () {
  94265. return this._zoomStopsAnimation;
  94266. },
  94267. /**
  94268. * Sets the flag that indicates if user zooming should stop animation.
  94269. */
  94270. set: function (flag) {
  94271. this._zoomStopsAnimation = flag;
  94272. },
  94273. enumerable: true,
  94274. configurable: true
  94275. });
  94276. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94277. /**
  94278. * Gets the transition time when framing the mesh, in milliseconds
  94279. */
  94280. get: function () {
  94281. return this._framingTime;
  94282. },
  94283. /**
  94284. * Sets the transition time when framing the mesh, in milliseconds
  94285. */
  94286. set: function (time) {
  94287. this._framingTime = time;
  94288. },
  94289. enumerable: true,
  94290. configurable: true
  94291. });
  94292. FramingBehavior.prototype.init = function () {
  94293. // Do notihng
  94294. };
  94295. FramingBehavior.prototype.attach = function (camera) {
  94296. var _this = this;
  94297. this._attachedCamera = camera;
  94298. var scene = this._attachedCamera.getScene();
  94299. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94300. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94301. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94302. _this._isPointerDown = true;
  94303. return;
  94304. }
  94305. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94306. _this._isPointerDown = false;
  94307. }
  94308. });
  94309. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94310. if (mesh) {
  94311. _this.zoomOnMesh(mesh);
  94312. }
  94313. });
  94314. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94315. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94316. _this._applyUserInteraction();
  94317. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94318. // back to the default position after a given timeout
  94319. _this._maintainCameraAboveGround();
  94320. });
  94321. };
  94322. FramingBehavior.prototype.detach = function () {
  94323. if (!this._attachedCamera) {
  94324. return;
  94325. }
  94326. var scene = this._attachedCamera.getScene();
  94327. if (this._onPrePointerObservableObserver) {
  94328. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94329. }
  94330. if (this._onAfterCheckInputsObserver) {
  94331. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94332. }
  94333. if (this._onMeshTargetChangedObserver) {
  94334. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94335. }
  94336. this._attachedCamera = null;
  94337. };
  94338. /**
  94339. * Targets the given mesh and updates zoom level accordingly.
  94340. * @param mesh The mesh to target.
  94341. * @param radius Optional. If a cached radius position already exists, overrides default.
  94342. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94343. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94344. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94345. */
  94346. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94347. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94348. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94349. mesh.computeWorldMatrix(true);
  94350. var boundingBox = mesh.getBoundingInfo().boundingBox;
  94351. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  94352. };
  94353. /**
  94354. * Targets the given mesh with its children and updates zoom level accordingly.
  94355. * @param mesh The mesh to target.
  94356. * @param radius Optional. If a cached radius position already exists, overrides default.
  94357. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94358. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94359. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94360. */
  94361. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94362. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94363. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94364. mesh.computeWorldMatrix(true);
  94365. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  94366. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  94367. };
  94368. /**
  94369. * Targets the given meshes with their children and updates zoom level accordingly.
  94370. * @param meshes The mesh to target.
  94371. * @param radius Optional. If a cached radius position already exists, overrides default.
  94372. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94373. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94374. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94375. */
  94376. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  94377. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94378. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94379. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94380. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  94381. for (var i = 0; i < meshes.length; i++) {
  94382. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  94383. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  94384. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  94385. }
  94386. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  94387. };
  94388. /**
  94389. * Targets the given mesh and updates zoom level accordingly.
  94390. * @param mesh The mesh to target.
  94391. * @param radius Optional. If a cached radius position already exists, overrides default.
  94392. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94393. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94394. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94395. */
  94396. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  94397. var _this = this;
  94398. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94399. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94400. var zoomTarget;
  94401. if (!this._attachedCamera) {
  94402. return;
  94403. }
  94404. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  94405. var bottom = minimumWorld.y;
  94406. var top = maximumWorld.y;
  94407. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  94408. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  94409. if (focusOnOriginXZ) {
  94410. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  94411. }
  94412. else {
  94413. var centerWorld = minimumWorld.add(radiusWorld);
  94414. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  94415. }
  94416. if (!this._vectorTransition) {
  94417. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  94418. }
  94419. this._betaIsAnimating = true;
  94420. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  94421. if (animatable) {
  94422. this._animatables.push(animatable);
  94423. }
  94424. // sets the radius and lower radius bounds
  94425. // Small delta ensures camera is not always at lower zoom limit.
  94426. var radius = 0;
  94427. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  94428. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94429. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  94430. radius = position;
  94431. }
  94432. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94433. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94434. if (this._attachedCamera.lowerRadiusLimit === null) {
  94435. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  94436. }
  94437. }
  94438. // Set sensibilities
  94439. var extend = maximumWorld.subtract(minimumWorld).length();
  94440. this._attachedCamera.panningSensibility = 5000 / extend;
  94441. this._attachedCamera.wheelPrecision = 100 / radius;
  94442. // transition to new radius
  94443. if (!this._radiusTransition) {
  94444. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94445. }
  94446. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  94447. _this.stopAllAnimations();
  94448. if (onAnimationEnd) {
  94449. onAnimationEnd();
  94450. }
  94451. if (_this._attachedCamera) {
  94452. _this._attachedCamera.storeState();
  94453. }
  94454. });
  94455. if (animatable) {
  94456. this._animatables.push(animatable);
  94457. }
  94458. };
  94459. /**
  94460. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  94461. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  94462. * frustum width.
  94463. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  94464. * to fully enclose the mesh in the viewing frustum.
  94465. */
  94466. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  94467. var size = maximumWorld.subtract(minimumWorld);
  94468. var boxVectorGlobalDiagonal = size.length();
  94469. var frustumSlope = this._getFrustumSlope();
  94470. // Formula for setting distance
  94471. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  94472. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  94473. // Horizon distance
  94474. var radius = radiusWithoutFraming * this._radiusScale;
  94475. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  94476. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  94477. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  94478. var camera = this._attachedCamera;
  94479. if (!camera) {
  94480. return 0;
  94481. }
  94482. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94483. // Don't exceed the requested limit
  94484. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  94485. }
  94486. // Don't exceed the upper radius limit
  94487. if (camera.upperRadiusLimit) {
  94488. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  94489. }
  94490. return distance;
  94491. };
  94492. /**
  94493. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  94494. * is automatically returned to its default position (expected to be above ground plane).
  94495. */
  94496. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  94497. var _this = this;
  94498. if (this._elevationReturnTime < 0) {
  94499. return;
  94500. }
  94501. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  94502. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  94503. var limitBeta = Math.PI * 0.5;
  94504. // Bring the camera back up if below the ground plane
  94505. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  94506. this._betaIsAnimating = true;
  94507. //Transition to new position
  94508. this.stopAllAnimations();
  94509. if (!this._betaTransition) {
  94510. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94511. }
  94512. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  94513. _this._clearAnimationLocks();
  94514. _this.stopAllAnimations();
  94515. });
  94516. if (animatabe) {
  94517. this._animatables.push(animatabe);
  94518. }
  94519. }
  94520. };
  94521. /**
  94522. * Returns the frustum slope based on the canvas ratio and camera FOV
  94523. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  94524. */
  94525. FramingBehavior.prototype._getFrustumSlope = function () {
  94526. // Calculate the viewport ratio
  94527. // Aspect Ratio is Height/Width.
  94528. var camera = this._attachedCamera;
  94529. if (!camera) {
  94530. return BABYLON.Vector2.Zero();
  94531. }
  94532. var engine = camera.getScene().getEngine();
  94533. var aspectRatio = engine.getAspectRatio(camera);
  94534. // Camera FOV is the vertical field of view (top-bottom) in radians.
  94535. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  94536. var frustumSlopeY = Math.tan(camera.fov / 2);
  94537. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  94538. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  94539. // along the forward vector.
  94540. var frustumSlopeX = frustumSlopeY * aspectRatio;
  94541. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  94542. };
  94543. /**
  94544. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  94545. */
  94546. FramingBehavior.prototype._clearAnimationLocks = function () {
  94547. this._betaIsAnimating = false;
  94548. };
  94549. /**
  94550. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94551. */
  94552. FramingBehavior.prototype._applyUserInteraction = function () {
  94553. if (this.isUserIsMoving) {
  94554. this._lastInteractionTime = BABYLON.Tools.Now;
  94555. this.stopAllAnimations();
  94556. this._clearAnimationLocks();
  94557. }
  94558. };
  94559. /**
  94560. * Stops and removes all animations that have been applied to the camera
  94561. */
  94562. FramingBehavior.prototype.stopAllAnimations = function () {
  94563. if (this._attachedCamera) {
  94564. this._attachedCamera.animations = [];
  94565. }
  94566. while (this._animatables.length) {
  94567. if (this._animatables[0]) {
  94568. this._animatables[0].onAnimationEnd = null;
  94569. this._animatables[0].stop();
  94570. }
  94571. this._animatables.shift();
  94572. }
  94573. };
  94574. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  94575. /**
  94576. * Gets a value indicating if the user is moving the camera
  94577. */
  94578. get: function () {
  94579. if (!this._attachedCamera) {
  94580. return false;
  94581. }
  94582. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94583. this._attachedCamera.inertialBetaOffset !== 0 ||
  94584. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94585. this._attachedCamera.inertialPanningX !== 0 ||
  94586. this._attachedCamera.inertialPanningY !== 0 ||
  94587. this._isPointerDown;
  94588. },
  94589. enumerable: true,
  94590. configurable: true
  94591. });
  94592. /**
  94593. * The easing function used by animations
  94594. */
  94595. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  94596. /**
  94597. * The easing mode used by animations
  94598. */
  94599. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  94600. // Statics
  94601. /**
  94602. * The camera can move all the way towards the mesh.
  94603. */
  94604. FramingBehavior.IgnoreBoundsSizeMode = 0;
  94605. /**
  94606. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  94607. */
  94608. FramingBehavior.FitFrustumSidesMode = 1;
  94609. return FramingBehavior;
  94610. }());
  94611. BABYLON.FramingBehavior = FramingBehavior;
  94612. })(BABYLON || (BABYLON = {}));
  94613. //# sourceMappingURL=babylon.framingBehavior.js.map
  94614. var BABYLON;
  94615. (function (BABYLON) {
  94616. /**
  94617. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  94618. */
  94619. var BouncingBehavior = /** @class */ (function () {
  94620. function BouncingBehavior() {
  94621. /**
  94622. * The duration of the animation, in milliseconds
  94623. */
  94624. this.transitionDuration = 450;
  94625. /**
  94626. * Length of the distance animated by the transition when lower radius is reached
  94627. */
  94628. this.lowerRadiusTransitionRange = 2;
  94629. /**
  94630. * Length of the distance animated by the transition when upper radius is reached
  94631. */
  94632. this.upperRadiusTransitionRange = -2;
  94633. this._autoTransitionRange = false;
  94634. // Animations
  94635. this._radiusIsAnimating = false;
  94636. this._radiusBounceTransition = null;
  94637. this._animatables = new Array();
  94638. }
  94639. Object.defineProperty(BouncingBehavior.prototype, "name", {
  94640. get: function () {
  94641. return "Bouncing";
  94642. },
  94643. enumerable: true,
  94644. configurable: true
  94645. });
  94646. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  94647. /**
  94648. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94649. */
  94650. get: function () {
  94651. return this._autoTransitionRange;
  94652. },
  94653. /**
  94654. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94655. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  94656. */
  94657. set: function (value) {
  94658. var _this = this;
  94659. if (this._autoTransitionRange === value) {
  94660. return;
  94661. }
  94662. this._autoTransitionRange = value;
  94663. var camera = this._attachedCamera;
  94664. if (!camera) {
  94665. return;
  94666. }
  94667. if (value) {
  94668. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94669. if (!mesh) {
  94670. return;
  94671. }
  94672. mesh.computeWorldMatrix(true);
  94673. var diagonal = mesh.getBoundingInfo().diagonalLength;
  94674. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  94675. _this.upperRadiusTransitionRange = diagonal * 0.05;
  94676. });
  94677. }
  94678. else if (this._onMeshTargetChangedObserver) {
  94679. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94680. }
  94681. },
  94682. enumerable: true,
  94683. configurable: true
  94684. });
  94685. BouncingBehavior.prototype.init = function () {
  94686. // Do notihng
  94687. };
  94688. BouncingBehavior.prototype.attach = function (camera) {
  94689. var _this = this;
  94690. this._attachedCamera = camera;
  94691. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94692. if (!_this._attachedCamera) {
  94693. return;
  94694. }
  94695. // Add the bounce animation to the lower radius limit
  94696. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  94697. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  94698. }
  94699. // Add the bounce animation to the upper radius limit
  94700. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  94701. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  94702. }
  94703. });
  94704. };
  94705. BouncingBehavior.prototype.detach = function () {
  94706. if (!this._attachedCamera) {
  94707. return;
  94708. }
  94709. if (this._onAfterCheckInputsObserver) {
  94710. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94711. }
  94712. if (this._onMeshTargetChangedObserver) {
  94713. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94714. }
  94715. this._attachedCamera = null;
  94716. };
  94717. /**
  94718. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  94719. * @param radiusLimit The limit to check against.
  94720. * @return Bool to indicate if at limit.
  94721. */
  94722. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  94723. if (!this._attachedCamera) {
  94724. return false;
  94725. }
  94726. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  94727. return true;
  94728. }
  94729. return false;
  94730. };
  94731. /**
  94732. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  94733. * @param radiusDelta The delta by which to animate to. Can be negative.
  94734. */
  94735. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  94736. var _this = this;
  94737. if (!this._attachedCamera) {
  94738. return;
  94739. }
  94740. if (!this._radiusBounceTransition) {
  94741. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  94742. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  94743. }
  94744. // Prevent zoom until bounce has completed
  94745. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  94746. this._attachedCamera.wheelPrecision = Infinity;
  94747. this._attachedCamera.inertialRadiusOffset = 0;
  94748. // Animate to the radius limit
  94749. this.stopAllAnimations();
  94750. this._radiusIsAnimating = true;
  94751. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  94752. if (animatable) {
  94753. this._animatables.push(animatable);
  94754. }
  94755. };
  94756. /**
  94757. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  94758. */
  94759. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94760. this._radiusIsAnimating = false;
  94761. if (this._attachedCamera) {
  94762. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94763. }
  94764. };
  94765. /**
  94766. * Stops and removes all animations that have been applied to the camera
  94767. */
  94768. BouncingBehavior.prototype.stopAllAnimations = function () {
  94769. if (this._attachedCamera) {
  94770. this._attachedCamera.animations = [];
  94771. }
  94772. while (this._animatables.length) {
  94773. this._animatables[0].onAnimationEnd = null;
  94774. this._animatables[0].stop();
  94775. this._animatables.shift();
  94776. }
  94777. };
  94778. /**
  94779. * The easing function used by animations
  94780. */
  94781. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  94782. /**
  94783. * The easing mode used by animations
  94784. */
  94785. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  94786. return BouncingBehavior;
  94787. }());
  94788. BABYLON.BouncingBehavior = BouncingBehavior;
  94789. })(BABYLON || (BABYLON = {}));
  94790. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  94791. var BABYLON;
  94792. (function (BABYLON) {
  94793. var AutoRotationBehavior = /** @class */ (function () {
  94794. function AutoRotationBehavior() {
  94795. this._zoomStopsAnimation = false;
  94796. this._idleRotationSpeed = 0.05;
  94797. this._idleRotationWaitTime = 2000;
  94798. this._idleRotationSpinupTime = 2000;
  94799. this._isPointerDown = false;
  94800. this._lastFrameTime = null;
  94801. this._lastInteractionTime = -Infinity;
  94802. this._cameraRotationSpeed = 0;
  94803. this._lastFrameRadius = 0;
  94804. }
  94805. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  94806. get: function () {
  94807. return "AutoRotation";
  94808. },
  94809. enumerable: true,
  94810. configurable: true
  94811. });
  94812. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  94813. /**
  94814. * Gets the flag that indicates if user zooming should stop animation.
  94815. */
  94816. get: function () {
  94817. return this._zoomStopsAnimation;
  94818. },
  94819. /**
  94820. * Sets the flag that indicates if user zooming should stop animation.
  94821. */
  94822. set: function (flag) {
  94823. this._zoomStopsAnimation = flag;
  94824. },
  94825. enumerable: true,
  94826. configurable: true
  94827. });
  94828. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  94829. /**
  94830. * Gets the default speed at which the camera rotates around the model.
  94831. */
  94832. get: function () {
  94833. return this._idleRotationSpeed;
  94834. },
  94835. /**
  94836. * Sets the default speed at which the camera rotates around the model.
  94837. */
  94838. set: function (speed) {
  94839. this._idleRotationSpeed = speed;
  94840. },
  94841. enumerable: true,
  94842. configurable: true
  94843. });
  94844. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  94845. /**
  94846. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  94847. */
  94848. get: function () {
  94849. return this._idleRotationWaitTime;
  94850. },
  94851. /**
  94852. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  94853. */
  94854. set: function (time) {
  94855. this._idleRotationWaitTime = time;
  94856. },
  94857. enumerable: true,
  94858. configurable: true
  94859. });
  94860. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  94861. /**
  94862. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94863. */
  94864. get: function () {
  94865. return this._idleRotationSpinupTime;
  94866. },
  94867. /**
  94868. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94869. */
  94870. set: function (time) {
  94871. this._idleRotationSpinupTime = time;
  94872. },
  94873. enumerable: true,
  94874. configurable: true
  94875. });
  94876. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  94877. /**
  94878. * Gets a value indicating if the camera is currently rotating because of this behavior
  94879. */
  94880. get: function () {
  94881. return Math.abs(this._cameraRotationSpeed) > 0;
  94882. },
  94883. enumerable: true,
  94884. configurable: true
  94885. });
  94886. AutoRotationBehavior.prototype.init = function () {
  94887. // Do notihng
  94888. };
  94889. AutoRotationBehavior.prototype.attach = function (camera) {
  94890. var _this = this;
  94891. this._attachedCamera = camera;
  94892. var scene = this._attachedCamera.getScene();
  94893. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94894. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94895. _this._isPointerDown = true;
  94896. return;
  94897. }
  94898. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94899. _this._isPointerDown = false;
  94900. }
  94901. });
  94902. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94903. var now = BABYLON.Tools.Now;
  94904. var dt = 0;
  94905. if (_this._lastFrameTime != null) {
  94906. dt = now - _this._lastFrameTime;
  94907. }
  94908. _this._lastFrameTime = now;
  94909. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94910. _this._applyUserInteraction();
  94911. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  94912. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  94913. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  94914. // Step camera rotation by rotation speed
  94915. if (_this._attachedCamera) {
  94916. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  94917. }
  94918. });
  94919. };
  94920. AutoRotationBehavior.prototype.detach = function () {
  94921. if (!this._attachedCamera) {
  94922. return;
  94923. }
  94924. var scene = this._attachedCamera.getScene();
  94925. if (this._onPrePointerObservableObserver) {
  94926. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94927. }
  94928. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94929. this._attachedCamera = null;
  94930. };
  94931. /**
  94932. * Returns true if user is scrolling.
  94933. * @return true if user is scrolling.
  94934. */
  94935. AutoRotationBehavior.prototype._userIsZooming = function () {
  94936. if (!this._attachedCamera) {
  94937. return false;
  94938. }
  94939. return this._attachedCamera.inertialRadiusOffset !== 0;
  94940. };
  94941. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  94942. if (!this._attachedCamera) {
  94943. return false;
  94944. }
  94945. var zoomHasHitLimit = false;
  94946. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  94947. zoomHasHitLimit = true;
  94948. }
  94949. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  94950. this._lastFrameRadius = this._attachedCamera.radius;
  94951. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  94952. };
  94953. /**
  94954. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94955. */
  94956. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  94957. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  94958. this._lastInteractionTime = BABYLON.Tools.Now;
  94959. }
  94960. };
  94961. // Tools
  94962. AutoRotationBehavior.prototype._userIsMoving = function () {
  94963. if (!this._attachedCamera) {
  94964. return false;
  94965. }
  94966. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94967. this._attachedCamera.inertialBetaOffset !== 0 ||
  94968. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94969. this._attachedCamera.inertialPanningX !== 0 ||
  94970. this._attachedCamera.inertialPanningY !== 0 ||
  94971. this._isPointerDown;
  94972. };
  94973. return AutoRotationBehavior;
  94974. }());
  94975. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  94976. })(BABYLON || (BABYLON = {}));
  94977. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  94978. var BABYLON;
  94979. (function (BABYLON) {
  94980. var NullEngineOptions = /** @class */ (function () {
  94981. function NullEngineOptions() {
  94982. this.renderWidth = 512;
  94983. this.renderHeight = 256;
  94984. this.textureSize = 512;
  94985. this.deterministicLockstep = false;
  94986. this.lockstepMaxSteps = 4;
  94987. }
  94988. return NullEngineOptions;
  94989. }());
  94990. BABYLON.NullEngineOptions = NullEngineOptions;
  94991. /**
  94992. * The null engine class provides support for headless version of babylon.js.
  94993. * This can be used in server side scenario or for testing purposes
  94994. */
  94995. var NullEngine = /** @class */ (function (_super) {
  94996. __extends(NullEngine, _super);
  94997. function NullEngine(options) {
  94998. if (options === void 0) { options = new NullEngineOptions(); }
  94999. var _this = _super.call(this, null) || this;
  95000. if (options.deterministicLockstep === undefined) {
  95001. options.deterministicLockstep = false;
  95002. }
  95003. if (options.lockstepMaxSteps === undefined) {
  95004. options.lockstepMaxSteps = 4;
  95005. }
  95006. _this._options = options;
  95007. // Init caps
  95008. // We consider we are on a webgl1 capable device
  95009. _this._caps = new BABYLON.EngineCapabilities();
  95010. _this._caps.maxTexturesImageUnits = 16;
  95011. _this._caps.maxVertexTextureImageUnits = 16;
  95012. _this._caps.maxTextureSize = 512;
  95013. _this._caps.maxCubemapTextureSize = 512;
  95014. _this._caps.maxRenderTextureSize = 512;
  95015. _this._caps.maxVertexAttribs = 16;
  95016. _this._caps.maxVaryingVectors = 16;
  95017. _this._caps.maxFragmentUniformVectors = 16;
  95018. _this._caps.maxVertexUniformVectors = 16;
  95019. // Extensions
  95020. _this._caps.standardDerivatives = false;
  95021. _this._caps.astc = null;
  95022. _this._caps.s3tc = null;
  95023. _this._caps.pvrtc = null;
  95024. _this._caps.etc1 = null;
  95025. _this._caps.etc2 = null;
  95026. _this._caps.textureAnisotropicFilterExtension = null;
  95027. _this._caps.maxAnisotropy = 0;
  95028. _this._caps.uintIndices = false;
  95029. _this._caps.fragmentDepthSupported = false;
  95030. _this._caps.highPrecisionShaderSupported = true;
  95031. _this._caps.colorBufferFloat = false;
  95032. _this._caps.textureFloat = false;
  95033. _this._caps.textureFloatLinearFiltering = false;
  95034. _this._caps.textureFloatRender = false;
  95035. _this._caps.textureHalfFloat = false;
  95036. _this._caps.textureHalfFloatLinearFiltering = false;
  95037. _this._caps.textureHalfFloatRender = false;
  95038. _this._caps.textureLOD = false;
  95039. _this._caps.drawBuffersExtension = false;
  95040. _this._caps.depthTextureExtension = false;
  95041. _this._caps.vertexArrayObject = false;
  95042. _this._caps.instancedArrays = false;
  95043. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  95044. // Wrappers
  95045. if (typeof URL === "undefined") {
  95046. URL = {
  95047. createObjectURL: function () { },
  95048. revokeObjectURL: function () { }
  95049. };
  95050. }
  95051. if (typeof Blob === "undefined") {
  95052. Blob = function () { };
  95053. }
  95054. return _this;
  95055. }
  95056. NullEngine.prototype.isDeterministicLockStep = function () {
  95057. return this._options.deterministicLockstep;
  95058. };
  95059. NullEngine.prototype.getLockstepMaxSteps = function () {
  95060. return this._options.lockstepMaxSteps;
  95061. };
  95062. NullEngine.prototype.getHardwareScalingLevel = function () {
  95063. return 1.0;
  95064. };
  95065. NullEngine.prototype.createVertexBuffer = function (vertices) {
  95066. return {
  95067. capacity: 0,
  95068. references: 1,
  95069. is32Bits: false
  95070. };
  95071. };
  95072. NullEngine.prototype.createIndexBuffer = function (indices) {
  95073. return {
  95074. capacity: 0,
  95075. references: 1,
  95076. is32Bits: false
  95077. };
  95078. };
  95079. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  95080. if (stencil === void 0) { stencil = false; }
  95081. };
  95082. NullEngine.prototype.getRenderWidth = function (useScreen) {
  95083. if (useScreen === void 0) { useScreen = false; }
  95084. if (!useScreen && this._currentRenderTarget) {
  95085. return this._currentRenderTarget.width;
  95086. }
  95087. return this._options.renderWidth;
  95088. };
  95089. NullEngine.prototype.getRenderHeight = function (useScreen) {
  95090. if (useScreen === void 0) { useScreen = false; }
  95091. if (!useScreen && this._currentRenderTarget) {
  95092. return this._currentRenderTarget.height;
  95093. }
  95094. return this._options.renderHeight;
  95095. };
  95096. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  95097. this._cachedViewport = viewport;
  95098. };
  95099. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  95100. return {
  95101. transformFeedback: null,
  95102. __SPECTOR_rebuildProgram: null
  95103. };
  95104. };
  95105. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  95106. return [];
  95107. };
  95108. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  95109. return [];
  95110. };
  95111. NullEngine.prototype.bindSamplers = function (effect) {
  95112. this._currentEffect = null;
  95113. };
  95114. NullEngine.prototype.enableEffect = function (effect) {
  95115. this._currentEffect = effect;
  95116. if (effect.onBind) {
  95117. effect.onBind(effect);
  95118. }
  95119. effect.onBindObservable.notifyObservers(effect);
  95120. };
  95121. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  95122. if (zOffset === void 0) { zOffset = 0; }
  95123. if (reverseSide === void 0) { reverseSide = false; }
  95124. };
  95125. NullEngine.prototype.setIntArray = function (uniform, array) {
  95126. };
  95127. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  95128. };
  95129. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  95130. };
  95131. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  95132. };
  95133. NullEngine.prototype.setFloatArray = function (uniform, array) {
  95134. };
  95135. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  95136. };
  95137. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  95138. };
  95139. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  95140. };
  95141. NullEngine.prototype.setArray = function (uniform, array) {
  95142. };
  95143. NullEngine.prototype.setArray2 = function (uniform, array) {
  95144. };
  95145. NullEngine.prototype.setArray3 = function (uniform, array) {
  95146. };
  95147. NullEngine.prototype.setArray4 = function (uniform, array) {
  95148. };
  95149. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  95150. };
  95151. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  95152. };
  95153. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  95154. };
  95155. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  95156. };
  95157. NullEngine.prototype.setFloat = function (uniform, value) {
  95158. };
  95159. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  95160. };
  95161. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  95162. };
  95163. NullEngine.prototype.setBool = function (uniform, bool) {
  95164. };
  95165. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  95166. };
  95167. NullEngine.prototype.setColor3 = function (uniform, color3) {
  95168. };
  95169. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  95170. };
  95171. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  95172. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  95173. if (this._alphaMode === mode) {
  95174. return;
  95175. }
  95176. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  95177. if (!noDepthWriteChange) {
  95178. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  95179. }
  95180. this._alphaMode = mode;
  95181. };
  95182. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  95183. };
  95184. NullEngine.prototype.wipeCaches = function (bruteForce) {
  95185. if (this.preventCacheWipeBetweenFrames) {
  95186. return;
  95187. }
  95188. this.resetTextureCache();
  95189. this._currentEffect = null;
  95190. if (bruteForce) {
  95191. this._currentProgram = null;
  95192. this._stencilState.reset();
  95193. this._depthCullingState.reset();
  95194. this._alphaState.reset();
  95195. }
  95196. this._cachedVertexBuffers = null;
  95197. this._cachedIndexBuffer = null;
  95198. this._cachedEffectForVertexBuffers = null;
  95199. };
  95200. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  95201. };
  95202. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  95203. };
  95204. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  95205. };
  95206. NullEngine.prototype._createTexture = function () {
  95207. return {};
  95208. };
  95209. NullEngine.prototype._releaseTexture = function (texture) {
  95210. };
  95211. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  95212. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95213. if (onLoad === void 0) { onLoad = null; }
  95214. if (onError === void 0) { onError = null; }
  95215. if (buffer === void 0) { buffer = null; }
  95216. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  95217. var url = String(urlArg);
  95218. texture.url = url;
  95219. texture.generateMipMaps = !noMipmap;
  95220. texture.samplingMode = samplingMode;
  95221. texture.invertY = invertY;
  95222. texture.baseWidth = this._options.textureSize;
  95223. texture.baseHeight = this._options.textureSize;
  95224. texture.width = this._options.textureSize;
  95225. texture.height = this._options.textureSize;
  95226. if (format) {
  95227. texture.format = format;
  95228. }
  95229. texture.isReady = true;
  95230. if (onLoad) {
  95231. onLoad();
  95232. }
  95233. return texture;
  95234. };
  95235. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  95236. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  95237. if (options !== undefined && typeof options === "object") {
  95238. fullOptions.generateMipMaps = options.generateMipMaps;
  95239. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  95240. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  95241. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95242. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95243. }
  95244. else {
  95245. fullOptions.generateMipMaps = options;
  95246. fullOptions.generateDepthBuffer = true;
  95247. fullOptions.generateStencilBuffer = false;
  95248. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95249. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95250. }
  95251. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95252. var width = size.width || size;
  95253. var height = size.height || size;
  95254. texture._depthStencilBuffer = {};
  95255. texture._framebuffer = {};
  95256. texture.baseWidth = width;
  95257. texture.baseHeight = height;
  95258. texture.width = width;
  95259. texture.height = height;
  95260. texture.isReady = true;
  95261. texture.samples = 1;
  95262. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95263. texture.samplingMode = fullOptions.samplingMode;
  95264. texture.type = fullOptions.type;
  95265. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95266. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95267. return texture;
  95268. };
  95269. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95270. texture.samplingMode = samplingMode;
  95271. };
  95272. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95273. if (this._currentRenderTarget) {
  95274. this.unBindFramebuffer(this._currentRenderTarget);
  95275. }
  95276. this._currentRenderTarget = texture;
  95277. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95278. if (this._cachedViewport && !forceFullscreenViewport) {
  95279. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95280. }
  95281. };
  95282. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95283. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95284. this._currentRenderTarget = null;
  95285. if (onBeforeUnbind) {
  95286. if (texture._MSAAFramebuffer) {
  95287. this._currentFramebuffer = texture._framebuffer;
  95288. }
  95289. onBeforeUnbind();
  95290. }
  95291. this._currentFramebuffer = null;
  95292. };
  95293. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95294. var vbo = {
  95295. capacity: 1,
  95296. references: 1,
  95297. is32Bits: false
  95298. };
  95299. return vbo;
  95300. };
  95301. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95302. if (offset === void 0) { offset = 0; }
  95303. };
  95304. /**
  95305. * Updates a dynamic vertex buffer.
  95306. * @param vertexBuffer the vertex buffer to update
  95307. * @param data the data used to update the vertex buffer
  95308. * @param byteOffset the byte offset of the data (optional)
  95309. * @param byteLength the byte length of the data (optional)
  95310. */
  95311. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95312. };
  95313. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95314. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95315. this._boundTexturesCache[this._activeChannel] = texture;
  95316. }
  95317. };
  95318. NullEngine.prototype._bindTexture = function (channel, texture) {
  95319. if (channel < 0) {
  95320. return;
  95321. }
  95322. this._bindTextureDirectly(0, texture);
  95323. };
  95324. NullEngine.prototype._releaseBuffer = function (buffer) {
  95325. buffer.references--;
  95326. if (buffer.references === 0) {
  95327. return true;
  95328. }
  95329. return false;
  95330. };
  95331. NullEngine.prototype.releaseEffects = function () {
  95332. };
  95333. return NullEngine;
  95334. }(BABYLON.Engine));
  95335. BABYLON.NullEngine = NullEngine;
  95336. })(BABYLON || (BABYLON = {}));
  95337. //# sourceMappingURL=babylon.nullEngine.js.map
  95338. var BABYLON;
  95339. (function (BABYLON) {
  95340. /**
  95341. * This class can be used to get instrumentation data from a Babylon engine
  95342. */
  95343. var EngineInstrumentation = /** @class */ (function () {
  95344. function EngineInstrumentation(engine) {
  95345. this.engine = engine;
  95346. this._captureGPUFrameTime = false;
  95347. this._gpuFrameTime = new BABYLON.PerfCounter();
  95348. this._captureShaderCompilationTime = false;
  95349. this._shaderCompilationTime = new BABYLON.PerfCounter();
  95350. // Observers
  95351. this._onBeginFrameObserver = null;
  95352. this._onEndFrameObserver = null;
  95353. this._onBeforeShaderCompilationObserver = null;
  95354. this._onAfterShaderCompilationObserver = null;
  95355. }
  95356. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  95357. // Properties
  95358. /**
  95359. * Gets the perf counter used for GPU frame time
  95360. */
  95361. get: function () {
  95362. return this._gpuFrameTime;
  95363. },
  95364. enumerable: true,
  95365. configurable: true
  95366. });
  95367. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  95368. /**
  95369. * Gets the GPU frame time capture status
  95370. */
  95371. get: function () {
  95372. return this._captureGPUFrameTime;
  95373. },
  95374. /**
  95375. * Enable or disable the GPU frame time capture
  95376. */
  95377. set: function (value) {
  95378. var _this = this;
  95379. if (value === this._captureGPUFrameTime) {
  95380. return;
  95381. }
  95382. this._captureGPUFrameTime = value;
  95383. if (value) {
  95384. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  95385. if (!_this._gpuFrameTimeToken) {
  95386. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  95387. }
  95388. });
  95389. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  95390. if (!_this._gpuFrameTimeToken) {
  95391. return;
  95392. }
  95393. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  95394. if (time > -1) {
  95395. _this._gpuFrameTimeToken = null;
  95396. _this._gpuFrameTime.fetchNewFrame();
  95397. _this._gpuFrameTime.addCount(time, true);
  95398. }
  95399. });
  95400. }
  95401. else {
  95402. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95403. this._onBeginFrameObserver = null;
  95404. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95405. this._onEndFrameObserver = null;
  95406. }
  95407. },
  95408. enumerable: true,
  95409. configurable: true
  95410. });
  95411. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  95412. /**
  95413. * Gets the perf counter used for shader compilation time
  95414. */
  95415. get: function () {
  95416. return this._shaderCompilationTime;
  95417. },
  95418. enumerable: true,
  95419. configurable: true
  95420. });
  95421. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  95422. /**
  95423. * Gets the shader compilation time capture status
  95424. */
  95425. get: function () {
  95426. return this._captureShaderCompilationTime;
  95427. },
  95428. /**
  95429. * Enable or disable the shader compilation time capture
  95430. */
  95431. set: function (value) {
  95432. var _this = this;
  95433. if (value === this._captureShaderCompilationTime) {
  95434. return;
  95435. }
  95436. this._captureShaderCompilationTime = value;
  95437. if (value) {
  95438. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  95439. _this._shaderCompilationTime.fetchNewFrame();
  95440. _this._shaderCompilationTime.beginMonitoring();
  95441. });
  95442. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  95443. _this._shaderCompilationTime.endMonitoring();
  95444. });
  95445. }
  95446. else {
  95447. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95448. this._onBeforeShaderCompilationObserver = null;
  95449. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95450. this._onAfterShaderCompilationObserver = null;
  95451. }
  95452. },
  95453. enumerable: true,
  95454. configurable: true
  95455. });
  95456. EngineInstrumentation.prototype.dispose = function () {
  95457. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95458. this._onBeginFrameObserver = null;
  95459. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95460. this._onEndFrameObserver = null;
  95461. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95462. this._onBeforeShaderCompilationObserver = null;
  95463. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95464. this._onAfterShaderCompilationObserver = null;
  95465. this.engine = null;
  95466. };
  95467. return EngineInstrumentation;
  95468. }());
  95469. BABYLON.EngineInstrumentation = EngineInstrumentation;
  95470. })(BABYLON || (BABYLON = {}));
  95471. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  95472. var BABYLON;
  95473. (function (BABYLON) {
  95474. /**
  95475. * This class can be used to get instrumentation data from a Babylon engine
  95476. */
  95477. var SceneInstrumentation = /** @class */ (function () {
  95478. function SceneInstrumentation(scene) {
  95479. var _this = this;
  95480. this.scene = scene;
  95481. this._captureActiveMeshesEvaluationTime = false;
  95482. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  95483. this._captureRenderTargetsRenderTime = false;
  95484. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  95485. this._captureFrameTime = false;
  95486. this._frameTime = new BABYLON.PerfCounter();
  95487. this._captureRenderTime = false;
  95488. this._renderTime = new BABYLON.PerfCounter();
  95489. this._captureInterFrameTime = false;
  95490. this._interFrameTime = new BABYLON.PerfCounter();
  95491. this._captureParticlesRenderTime = false;
  95492. this._particlesRenderTime = new BABYLON.PerfCounter();
  95493. this._captureSpritesRenderTime = false;
  95494. this._spritesRenderTime = new BABYLON.PerfCounter();
  95495. this._capturePhysicsTime = false;
  95496. this._physicsTime = new BABYLON.PerfCounter();
  95497. this._captureAnimationsTime = false;
  95498. this._animationsTime = new BABYLON.PerfCounter();
  95499. // Observers
  95500. this._onBeforeActiveMeshesEvaluationObserver = null;
  95501. this._onAfterActiveMeshesEvaluationObserver = null;
  95502. this._onBeforeRenderTargetsRenderObserver = null;
  95503. this._onAfterRenderTargetsRenderObserver = null;
  95504. this._onAfterRenderObserver = null;
  95505. this._onBeforeDrawPhaseObserver = null;
  95506. this._onAfterDrawPhaseObserver = null;
  95507. this._onBeforeAnimationsObserver = null;
  95508. this._onBeforeParticlesRenderingObserver = null;
  95509. this._onAfterParticlesRenderingObserver = null;
  95510. this._onBeforeSpritesRenderingObserver = null;
  95511. this._onAfterSpritesRenderingObserver = null;
  95512. this._onBeforePhysicsObserver = null;
  95513. this._onAfterPhysicsObserver = null;
  95514. this._onAfterAnimationsObserver = null;
  95515. // Before render
  95516. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  95517. if (_this._captureActiveMeshesEvaluationTime) {
  95518. _this._activeMeshesEvaluationTime.fetchNewFrame();
  95519. }
  95520. if (_this._captureRenderTargetsRenderTime) {
  95521. _this._renderTargetsRenderTime.fetchNewFrame();
  95522. }
  95523. if (_this._captureFrameTime) {
  95524. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  95525. _this._frameTime.beginMonitoring();
  95526. }
  95527. if (_this._captureInterFrameTime) {
  95528. _this._interFrameTime.endMonitoring();
  95529. }
  95530. if (_this._captureParticlesRenderTime) {
  95531. _this._particlesRenderTime.fetchNewFrame();
  95532. }
  95533. if (_this._captureSpritesRenderTime) {
  95534. _this._spritesRenderTime.fetchNewFrame();
  95535. }
  95536. if (_this._captureAnimationsTime) {
  95537. _this._animationsTime.beginMonitoring();
  95538. }
  95539. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  95540. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  95541. });
  95542. // After render
  95543. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  95544. if (_this._captureFrameTime) {
  95545. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  95546. _this._frameTime.endMonitoring();
  95547. }
  95548. if (_this._captureRenderTime) {
  95549. _this._renderTime.endMonitoring(false);
  95550. }
  95551. if (_this._captureInterFrameTime) {
  95552. _this._interFrameTime.beginMonitoring();
  95553. }
  95554. });
  95555. }
  95556. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  95557. // Properties
  95558. /**
  95559. * Gets the perf counter used for active meshes evaluation time
  95560. */
  95561. get: function () {
  95562. return this._activeMeshesEvaluationTime;
  95563. },
  95564. enumerable: true,
  95565. configurable: true
  95566. });
  95567. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  95568. /**
  95569. * Gets the active meshes evaluation time capture status
  95570. */
  95571. get: function () {
  95572. return this._captureActiveMeshesEvaluationTime;
  95573. },
  95574. /**
  95575. * Enable or disable the active meshes evaluation time capture
  95576. */
  95577. set: function (value) {
  95578. var _this = this;
  95579. if (value === this._captureActiveMeshesEvaluationTime) {
  95580. return;
  95581. }
  95582. this._captureActiveMeshesEvaluationTime = value;
  95583. if (value) {
  95584. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  95585. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  95586. _this._activeMeshesEvaluationTime.beginMonitoring();
  95587. });
  95588. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  95589. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  95590. _this._activeMeshesEvaluationTime.endMonitoring();
  95591. });
  95592. }
  95593. else {
  95594. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95595. this._onBeforeActiveMeshesEvaluationObserver = null;
  95596. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95597. this._onAfterActiveMeshesEvaluationObserver = null;
  95598. }
  95599. },
  95600. enumerable: true,
  95601. configurable: true
  95602. });
  95603. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  95604. /**
  95605. * Gets the perf counter used for render targets render time
  95606. */
  95607. get: function () {
  95608. return this._renderTargetsRenderTime;
  95609. },
  95610. enumerable: true,
  95611. configurable: true
  95612. });
  95613. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  95614. /**
  95615. * Gets the render targets render time capture status
  95616. */
  95617. get: function () {
  95618. return this._captureRenderTargetsRenderTime;
  95619. },
  95620. /**
  95621. * Enable or disable the render targets render time capture
  95622. */
  95623. set: function (value) {
  95624. var _this = this;
  95625. if (value === this._captureRenderTargetsRenderTime) {
  95626. return;
  95627. }
  95628. this._captureRenderTargetsRenderTime = value;
  95629. if (value) {
  95630. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  95631. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  95632. _this._renderTargetsRenderTime.beginMonitoring();
  95633. });
  95634. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  95635. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  95636. _this._renderTargetsRenderTime.endMonitoring(false);
  95637. });
  95638. }
  95639. else {
  95640. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95641. this._onBeforeRenderTargetsRenderObserver = null;
  95642. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95643. this._onAfterRenderTargetsRenderObserver = null;
  95644. }
  95645. },
  95646. enumerable: true,
  95647. configurable: true
  95648. });
  95649. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  95650. /**
  95651. * Gets the perf counter used for particles render time
  95652. */
  95653. get: function () {
  95654. return this._particlesRenderTime;
  95655. },
  95656. enumerable: true,
  95657. configurable: true
  95658. });
  95659. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  95660. /**
  95661. * Gets the particles render time capture status
  95662. */
  95663. get: function () {
  95664. return this._captureParticlesRenderTime;
  95665. },
  95666. /**
  95667. * Enable or disable the particles render time capture
  95668. */
  95669. set: function (value) {
  95670. var _this = this;
  95671. if (value === this._captureParticlesRenderTime) {
  95672. return;
  95673. }
  95674. this._captureParticlesRenderTime = value;
  95675. if (value) {
  95676. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  95677. BABYLON.Tools.StartPerformanceCounter("Particles");
  95678. _this._particlesRenderTime.beginMonitoring();
  95679. });
  95680. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  95681. BABYLON.Tools.EndPerformanceCounter("Particles");
  95682. _this._particlesRenderTime.endMonitoring(false);
  95683. });
  95684. }
  95685. else {
  95686. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95687. this._onBeforeParticlesRenderingObserver = null;
  95688. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95689. this._onAfterParticlesRenderingObserver = null;
  95690. }
  95691. },
  95692. enumerable: true,
  95693. configurable: true
  95694. });
  95695. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  95696. /**
  95697. * Gets the perf counter used for sprites render time
  95698. */
  95699. get: function () {
  95700. return this._spritesRenderTime;
  95701. },
  95702. enumerable: true,
  95703. configurable: true
  95704. });
  95705. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  95706. /**
  95707. * Gets the sprites render time capture status
  95708. */
  95709. get: function () {
  95710. return this._captureSpritesRenderTime;
  95711. },
  95712. /**
  95713. * Enable or disable the sprites render time capture
  95714. */
  95715. set: function (value) {
  95716. var _this = this;
  95717. if (value === this._captureSpritesRenderTime) {
  95718. return;
  95719. }
  95720. this._captureSpritesRenderTime = value;
  95721. if (value) {
  95722. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  95723. BABYLON.Tools.StartPerformanceCounter("Sprites");
  95724. _this._spritesRenderTime.beginMonitoring();
  95725. });
  95726. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  95727. BABYLON.Tools.EndPerformanceCounter("Sprites");
  95728. _this._spritesRenderTime.endMonitoring(false);
  95729. });
  95730. }
  95731. else {
  95732. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95733. this._onBeforeSpritesRenderingObserver = null;
  95734. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95735. this._onAfterSpritesRenderingObserver = null;
  95736. }
  95737. },
  95738. enumerable: true,
  95739. configurable: true
  95740. });
  95741. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  95742. /**
  95743. * Gets the perf counter used for physics time
  95744. */
  95745. get: function () {
  95746. return this._physicsTime;
  95747. },
  95748. enumerable: true,
  95749. configurable: true
  95750. });
  95751. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  95752. /**
  95753. * Gets the physics time capture status
  95754. */
  95755. get: function () {
  95756. return this._capturePhysicsTime;
  95757. },
  95758. /**
  95759. * Enable or disable the physics time capture
  95760. */
  95761. set: function (value) {
  95762. var _this = this;
  95763. if (value === this._capturePhysicsTime) {
  95764. return;
  95765. }
  95766. this._capturePhysicsTime = value;
  95767. if (value) {
  95768. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  95769. BABYLON.Tools.StartPerformanceCounter("Physics");
  95770. _this._physicsTime.beginMonitoring();
  95771. });
  95772. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  95773. BABYLON.Tools.EndPerformanceCounter("Physics");
  95774. _this._physicsTime.endMonitoring();
  95775. });
  95776. }
  95777. else {
  95778. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95779. this._onBeforePhysicsObserver = null;
  95780. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95781. this._onAfterPhysicsObserver = null;
  95782. }
  95783. },
  95784. enumerable: true,
  95785. configurable: true
  95786. });
  95787. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  95788. /**
  95789. * Gets the perf counter used for animations time
  95790. */
  95791. get: function () {
  95792. return this._animationsTime;
  95793. },
  95794. enumerable: true,
  95795. configurable: true
  95796. });
  95797. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  95798. /**
  95799. * Gets the animations time capture status
  95800. */
  95801. get: function () {
  95802. return this._captureAnimationsTime;
  95803. },
  95804. /**
  95805. * Enable or disable the animations time capture
  95806. */
  95807. set: function (value) {
  95808. var _this = this;
  95809. if (value === this._captureAnimationsTime) {
  95810. return;
  95811. }
  95812. this._captureAnimationsTime = value;
  95813. if (value) {
  95814. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  95815. _this._animationsTime.endMonitoring();
  95816. });
  95817. }
  95818. else {
  95819. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95820. this._onAfterAnimationsObserver = null;
  95821. }
  95822. },
  95823. enumerable: true,
  95824. configurable: true
  95825. });
  95826. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  95827. /**
  95828. * Gets the perf counter used for frame time capture
  95829. */
  95830. get: function () {
  95831. return this._frameTime;
  95832. },
  95833. enumerable: true,
  95834. configurable: true
  95835. });
  95836. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  95837. /**
  95838. * Gets the frame time capture status
  95839. */
  95840. get: function () {
  95841. return this._captureFrameTime;
  95842. },
  95843. /**
  95844. * Enable or disable the frame time capture
  95845. */
  95846. set: function (value) {
  95847. this._captureFrameTime = value;
  95848. },
  95849. enumerable: true,
  95850. configurable: true
  95851. });
  95852. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  95853. /**
  95854. * Gets the perf counter used for inter-frames time capture
  95855. */
  95856. get: function () {
  95857. return this._interFrameTime;
  95858. },
  95859. enumerable: true,
  95860. configurable: true
  95861. });
  95862. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  95863. /**
  95864. * Gets the inter-frames time capture status
  95865. */
  95866. get: function () {
  95867. return this._captureInterFrameTime;
  95868. },
  95869. /**
  95870. * Enable or disable the inter-frames time capture
  95871. */
  95872. set: function (value) {
  95873. this._captureInterFrameTime = value;
  95874. },
  95875. enumerable: true,
  95876. configurable: true
  95877. });
  95878. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  95879. /**
  95880. * Gets the perf counter used for render time capture
  95881. */
  95882. get: function () {
  95883. return this._renderTime;
  95884. },
  95885. enumerable: true,
  95886. configurable: true
  95887. });
  95888. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  95889. /**
  95890. * Gets the render time capture status
  95891. */
  95892. get: function () {
  95893. return this._captureRenderTime;
  95894. },
  95895. /**
  95896. * Enable or disable the render time capture
  95897. */
  95898. set: function (value) {
  95899. var _this = this;
  95900. if (value === this._captureRenderTime) {
  95901. return;
  95902. }
  95903. this._captureRenderTime = value;
  95904. if (value) {
  95905. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  95906. _this._renderTime.beginMonitoring();
  95907. BABYLON.Tools.StartPerformanceCounter("Main render");
  95908. });
  95909. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  95910. _this._renderTime.endMonitoring(false);
  95911. BABYLON.Tools.EndPerformanceCounter("Main render");
  95912. });
  95913. }
  95914. else {
  95915. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95916. this._onBeforeDrawPhaseObserver = null;
  95917. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95918. this._onAfterDrawPhaseObserver = null;
  95919. }
  95920. },
  95921. enumerable: true,
  95922. configurable: true
  95923. });
  95924. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  95925. /**
  95926. * Gets the perf counter used for draw calls
  95927. */
  95928. get: function () {
  95929. return this.scene.getEngine()._drawCalls;
  95930. },
  95931. enumerable: true,
  95932. configurable: true
  95933. });
  95934. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  95935. /**
  95936. * Gets the perf counter used for texture collisions
  95937. */
  95938. get: function () {
  95939. return this.scene.getEngine()._textureCollisions;
  95940. },
  95941. enumerable: true,
  95942. configurable: true
  95943. });
  95944. SceneInstrumentation.prototype.dispose = function () {
  95945. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  95946. this._onAfterRenderObserver = null;
  95947. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95948. this._onBeforeActiveMeshesEvaluationObserver = null;
  95949. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95950. this._onAfterActiveMeshesEvaluationObserver = null;
  95951. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95952. this._onBeforeRenderTargetsRenderObserver = null;
  95953. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95954. this._onAfterRenderTargetsRenderObserver = null;
  95955. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  95956. this._onBeforeAnimationsObserver = null;
  95957. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95958. this._onBeforeParticlesRenderingObserver = null;
  95959. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95960. this._onAfterParticlesRenderingObserver = null;
  95961. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95962. this._onBeforeSpritesRenderingObserver = null;
  95963. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95964. this._onAfterSpritesRenderingObserver = null;
  95965. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95966. this._onBeforeDrawPhaseObserver = null;
  95967. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95968. this._onAfterDrawPhaseObserver = null;
  95969. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95970. this._onBeforePhysicsObserver = null;
  95971. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95972. this._onAfterPhysicsObserver = null;
  95973. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95974. this._onAfterAnimationsObserver = null;
  95975. this.scene = null;
  95976. };
  95977. return SceneInstrumentation;
  95978. }());
  95979. BABYLON.SceneInstrumentation = SceneInstrumentation;
  95980. })(BABYLON || (BABYLON = {}));
  95981. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  95982. var BABYLON;
  95983. (function (BABYLON) {
  95984. /**
  95985. * @hidden
  95986. **/
  95987. var _TimeToken = /** @class */ (function () {
  95988. function _TimeToken() {
  95989. this._timeElapsedQueryEnded = false;
  95990. }
  95991. return _TimeToken;
  95992. }());
  95993. BABYLON._TimeToken = _TimeToken;
  95994. })(BABYLON || (BABYLON = {}));
  95995. //# sourceMappingURL=babylon.timeToken.js.map
  95996. var BABYLON;
  95997. (function (BABYLON) {
  95998. /**
  95999. * Background material defines definition.
  96000. * @hidden Mainly internal Use
  96001. */
  96002. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  96003. __extends(BackgroundMaterialDefines, _super);
  96004. /**
  96005. * Constructor of the defines.
  96006. */
  96007. function BackgroundMaterialDefines() {
  96008. var _this = _super.call(this) || this;
  96009. /**
  96010. * True if the diffuse texture is in use.
  96011. */
  96012. _this.DIFFUSE = false;
  96013. /**
  96014. * The direct UV channel to use.
  96015. */
  96016. _this.DIFFUSEDIRECTUV = 0;
  96017. /**
  96018. * True if the diffuse texture is in gamma space.
  96019. */
  96020. _this.GAMMADIFFUSE = false;
  96021. /**
  96022. * True if the diffuse texture has opacity in the alpha channel.
  96023. */
  96024. _this.DIFFUSEHASALPHA = false;
  96025. /**
  96026. * True if you want the material to fade to transparent at grazing angle.
  96027. */
  96028. _this.OPACITYFRESNEL = false;
  96029. /**
  96030. * True if an extra blur needs to be added in the reflection.
  96031. */
  96032. _this.REFLECTIONBLUR = false;
  96033. /**
  96034. * True if you want the material to fade to reflection at grazing angle.
  96035. */
  96036. _this.REFLECTIONFRESNEL = false;
  96037. /**
  96038. * True if you want the material to falloff as far as you move away from the scene center.
  96039. */
  96040. _this.REFLECTIONFALLOFF = false;
  96041. /**
  96042. * False if the current Webgl implementation does not support the texture lod extension.
  96043. */
  96044. _this.TEXTURELODSUPPORT = false;
  96045. /**
  96046. * True to ensure the data are premultiplied.
  96047. */
  96048. _this.PREMULTIPLYALPHA = false;
  96049. /**
  96050. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  96051. */
  96052. _this.USERGBCOLOR = false;
  96053. /**
  96054. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  96055. * stays aligned with the desired configuration.
  96056. */
  96057. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  96058. /**
  96059. * True to add noise in order to reduce the banding effect.
  96060. */
  96061. _this.NOISE = false;
  96062. /**
  96063. * is the reflection texture in BGR color scheme?
  96064. * Mainly used to solve a bug in ios10 video tag
  96065. */
  96066. _this.REFLECTIONBGR = false;
  96067. _this.IMAGEPROCESSING = false;
  96068. _this.VIGNETTE = false;
  96069. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  96070. _this.VIGNETTEBLENDMODEOPAQUE = false;
  96071. _this.TONEMAPPING = false;
  96072. _this.CONTRAST = false;
  96073. _this.COLORCURVES = false;
  96074. _this.COLORGRADING = false;
  96075. _this.COLORGRADING3D = false;
  96076. _this.SAMPLER3DGREENDEPTH = false;
  96077. _this.SAMPLER3DBGRMAP = false;
  96078. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  96079. _this.EXPOSURE = false;
  96080. // Reflection.
  96081. _this.REFLECTION = false;
  96082. _this.REFLECTIONMAP_3D = false;
  96083. _this.REFLECTIONMAP_SPHERICAL = false;
  96084. _this.REFLECTIONMAP_PLANAR = false;
  96085. _this.REFLECTIONMAP_CUBIC = false;
  96086. _this.REFLECTIONMAP_PROJECTION = false;
  96087. _this.REFLECTIONMAP_SKYBOX = false;
  96088. _this.REFLECTIONMAP_EXPLICIT = false;
  96089. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96090. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96091. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96092. _this.INVERTCUBICMAP = false;
  96093. _this.REFLECTIONMAP_OPPOSITEZ = false;
  96094. _this.LODINREFLECTIONALPHA = false;
  96095. _this.GAMMAREFLECTION = false;
  96096. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  96097. // Default BJS.
  96098. _this.MAINUV1 = false;
  96099. _this.MAINUV2 = false;
  96100. _this.UV1 = false;
  96101. _this.UV2 = false;
  96102. _this.CLIPPLANE = false;
  96103. _this.POINTSIZE = false;
  96104. _this.FOG = false;
  96105. _this.NORMAL = false;
  96106. _this.NUM_BONE_INFLUENCERS = 0;
  96107. _this.BonesPerMesh = 0;
  96108. _this.INSTANCES = false;
  96109. _this.SHADOWFLOAT = false;
  96110. _this.rebuild();
  96111. return _this;
  96112. }
  96113. return BackgroundMaterialDefines;
  96114. }(BABYLON.MaterialDefines));
  96115. /**
  96116. * Background material used to create an efficient environement around your scene.
  96117. */
  96118. var BackgroundMaterial = /** @class */ (function (_super) {
  96119. __extends(BackgroundMaterial, _super);
  96120. /**
  96121. * Instantiates a Background Material in the given scene
  96122. * @param name The friendly name of the material
  96123. * @param scene The scene to add the material to
  96124. */
  96125. function BackgroundMaterial(name, scene) {
  96126. var _this = _super.call(this, name, scene) || this;
  96127. /**
  96128. * Key light Color (multiply against the environement texture)
  96129. */
  96130. _this.primaryColor = BABYLON.Color3.White();
  96131. _this._primaryColorShadowLevel = 0;
  96132. _this._primaryColorHighlightLevel = 0;
  96133. /**
  96134. * Reflection Texture used in the material.
  96135. * Should be author in a specific way for the best result (refer to the documentation).
  96136. */
  96137. _this.reflectionTexture = null;
  96138. /**
  96139. * Reflection Texture level of blur.
  96140. *
  96141. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  96142. * texture twice.
  96143. */
  96144. _this.reflectionBlur = 0;
  96145. /**
  96146. * Diffuse Texture used in the material.
  96147. * Should be author in a specific way for the best result (refer to the documentation).
  96148. */
  96149. _this.diffuseTexture = null;
  96150. _this._shadowLights = null;
  96151. /**
  96152. * Specify the list of lights casting shadow on the material.
  96153. * All scene shadow lights will be included if null.
  96154. */
  96155. _this.shadowLights = null;
  96156. /**
  96157. * Helps adjusting the shadow to a softer level if required.
  96158. * 0 means black shadows and 1 means no shadows.
  96159. */
  96160. _this.shadowLevel = 0;
  96161. /**
  96162. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  96163. * It is usually zero but might be interesting to modify according to your setup.
  96164. */
  96165. _this.sceneCenter = BABYLON.Vector3.Zero();
  96166. /**
  96167. * This helps specifying that the material is falling off to the sky box at grazing angle.
  96168. * This helps ensuring a nice transition when the camera goes under the ground.
  96169. */
  96170. _this.opacityFresnel = true;
  96171. /**
  96172. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  96173. * This helps adding a mirror texture on the ground.
  96174. */
  96175. _this.reflectionFresnel = false;
  96176. /**
  96177. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  96178. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  96179. */
  96180. _this.reflectionFalloffDistance = 0.0;
  96181. /**
  96182. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  96183. */
  96184. _this.reflectionAmount = 1.0;
  96185. /**
  96186. * This specifies the weight of the reflection at grazing angle.
  96187. */
  96188. _this.reflectionReflectance0 = 0.05;
  96189. /**
  96190. * This specifies the weight of the reflection at a perpendicular point of view.
  96191. */
  96192. _this.reflectionReflectance90 = 0.5;
  96193. /**
  96194. * Helps to directly use the maps channels instead of their level.
  96195. */
  96196. _this.useRGBColor = true;
  96197. /**
  96198. * This helps reducing the banding effect that could occur on the background.
  96199. */
  96200. _this.enableNoise = false;
  96201. _this._fovMultiplier = 1.0;
  96202. /**
  96203. * Enable the FOV adjustment feature controlled by fovMultiplier.
  96204. */
  96205. _this.useEquirectangularFOV = false;
  96206. _this._maxSimultaneousLights = 4;
  96207. /**
  96208. * Number of Simultaneous lights allowed on the material.
  96209. */
  96210. _this.maxSimultaneousLights = 4;
  96211. /**
  96212. * Keep track of the image processing observer to allow dispose and replace.
  96213. */
  96214. _this._imageProcessingObserver = null;
  96215. /**
  96216. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  96217. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  96218. */
  96219. _this.switchToBGR = false;
  96220. // Temp values kept as cache in the material.
  96221. _this._renderTargets = new BABYLON.SmartArray(16);
  96222. _this._reflectionControls = BABYLON.Vector4.Zero();
  96223. _this._white = BABYLON.Color3.White();
  96224. _this._primaryShadowColor = BABYLON.Color3.Black();
  96225. _this._primaryHighlightColor = BABYLON.Color3.Black();
  96226. // Setup the default processing configuration to the scene.
  96227. _this._attachImageProcessingConfiguration(null);
  96228. _this.getRenderTargetTextures = function () {
  96229. _this._renderTargets.reset();
  96230. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  96231. _this._renderTargets.push(_this._diffuseTexture);
  96232. }
  96233. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  96234. _this._renderTargets.push(_this._reflectionTexture);
  96235. }
  96236. return _this._renderTargets;
  96237. };
  96238. return _this;
  96239. }
  96240. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  96241. /**
  96242. * Experimental Internal Use Only.
  96243. *
  96244. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96245. * This acts as a helper to set the primary color to a more "human friendly" value.
  96246. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96247. * output color as close as possible from the chosen value.
  96248. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96249. * part of lighting setup.)
  96250. */
  96251. get: function () {
  96252. return this.__perceptualColor;
  96253. },
  96254. set: function (value) {
  96255. this.__perceptualColor = value;
  96256. this._computePrimaryColorFromPerceptualColor();
  96257. this._markAllSubMeshesAsLightsDirty();
  96258. },
  96259. enumerable: true,
  96260. configurable: true
  96261. });
  96262. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96263. /**
  96264. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96265. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96266. */
  96267. get: function () {
  96268. return this._primaryColorShadowLevel;
  96269. },
  96270. set: function (value) {
  96271. this._primaryColorShadowLevel = value;
  96272. this._computePrimaryColors();
  96273. this._markAllSubMeshesAsLightsDirty();
  96274. },
  96275. enumerable: true,
  96276. configurable: true
  96277. });
  96278. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96279. /**
  96280. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96281. * The primary color is used at the level chosen to define what the white area would look.
  96282. */
  96283. get: function () {
  96284. return this._primaryColorHighlightLevel;
  96285. },
  96286. set: function (value) {
  96287. this._primaryColorHighlightLevel = value;
  96288. this._computePrimaryColors();
  96289. this._markAllSubMeshesAsLightsDirty();
  96290. },
  96291. enumerable: true,
  96292. configurable: true
  96293. });
  96294. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96295. /**
  96296. * Sets the reflection reflectance fresnel values according to the default standard
  96297. * empirically know to work well :-)
  96298. */
  96299. set: function (value) {
  96300. var reflectionWeight = value;
  96301. if (reflectionWeight < 0.5) {
  96302. reflectionWeight = reflectionWeight * 2.0;
  96303. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96304. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96305. }
  96306. else {
  96307. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96308. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96309. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96310. }
  96311. },
  96312. enumerable: true,
  96313. configurable: true
  96314. });
  96315. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96316. /**
  96317. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96318. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96319. * Recommended to be keep at 1.0 except for special cases.
  96320. */
  96321. get: function () {
  96322. return this._fovMultiplier;
  96323. },
  96324. set: function (value) {
  96325. if (isNaN(value)) {
  96326. value = 1.0;
  96327. }
  96328. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96329. },
  96330. enumerable: true,
  96331. configurable: true
  96332. });
  96333. /**
  96334. * Attaches a new image processing configuration to the PBR Material.
  96335. * @param configuration (if null the scene configuration will be use)
  96336. */
  96337. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  96338. var _this = this;
  96339. if (configuration === this._imageProcessingConfiguration) {
  96340. return;
  96341. }
  96342. // Detaches observer.
  96343. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96344. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96345. }
  96346. // Pick the scene configuration if needed.
  96347. if (!configuration) {
  96348. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  96349. }
  96350. else {
  96351. this._imageProcessingConfiguration = configuration;
  96352. }
  96353. // Attaches observer.
  96354. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  96355. _this._computePrimaryColorFromPerceptualColor();
  96356. _this._markAllSubMeshesAsImageProcessingDirty();
  96357. });
  96358. };
  96359. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  96360. /**
  96361. * Gets the image processing configuration used either in this material.
  96362. */
  96363. get: function () {
  96364. return this._imageProcessingConfiguration;
  96365. },
  96366. /**
  96367. * Sets the Default image processing configuration used either in the this material.
  96368. *
  96369. * If sets to null, the scene one is in use.
  96370. */
  96371. set: function (value) {
  96372. this._attachImageProcessingConfiguration(value);
  96373. // Ensure the effect will be rebuilt.
  96374. this._markAllSubMeshesAsTexturesDirty();
  96375. },
  96376. enumerable: true,
  96377. configurable: true
  96378. });
  96379. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  96380. /**
  96381. * Gets wether the color curves effect is enabled.
  96382. */
  96383. get: function () {
  96384. return this.imageProcessingConfiguration.colorCurvesEnabled;
  96385. },
  96386. /**
  96387. * Sets wether the color curves effect is enabled.
  96388. */
  96389. set: function (value) {
  96390. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  96391. },
  96392. enumerable: true,
  96393. configurable: true
  96394. });
  96395. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  96396. /**
  96397. * Gets wether the color grading effect is enabled.
  96398. */
  96399. get: function () {
  96400. return this.imageProcessingConfiguration.colorGradingEnabled;
  96401. },
  96402. /**
  96403. * Gets wether the color grading effect is enabled.
  96404. */
  96405. set: function (value) {
  96406. this.imageProcessingConfiguration.colorGradingEnabled = value;
  96407. },
  96408. enumerable: true,
  96409. configurable: true
  96410. });
  96411. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  96412. /**
  96413. * Gets wether tonemapping is enabled or not.
  96414. */
  96415. get: function () {
  96416. return this._imageProcessingConfiguration.toneMappingEnabled;
  96417. },
  96418. /**
  96419. * Sets wether tonemapping is enabled or not
  96420. */
  96421. set: function (value) {
  96422. this._imageProcessingConfiguration.toneMappingEnabled = value;
  96423. },
  96424. enumerable: true,
  96425. configurable: true
  96426. });
  96427. ;
  96428. ;
  96429. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  96430. /**
  96431. * The camera exposure used on this material.
  96432. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96433. * This corresponds to a photographic exposure.
  96434. */
  96435. get: function () {
  96436. return this._imageProcessingConfiguration.exposure;
  96437. },
  96438. /**
  96439. * The camera exposure used on this material.
  96440. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96441. * This corresponds to a photographic exposure.
  96442. */
  96443. set: function (value) {
  96444. this._imageProcessingConfiguration.exposure = value;
  96445. },
  96446. enumerable: true,
  96447. configurable: true
  96448. });
  96449. ;
  96450. ;
  96451. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  96452. /**
  96453. * Gets The camera contrast used on this material.
  96454. */
  96455. get: function () {
  96456. return this._imageProcessingConfiguration.contrast;
  96457. },
  96458. /**
  96459. * Sets The camera contrast used on this material.
  96460. */
  96461. set: function (value) {
  96462. this._imageProcessingConfiguration.contrast = value;
  96463. },
  96464. enumerable: true,
  96465. configurable: true
  96466. });
  96467. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  96468. /**
  96469. * Gets the Color Grading 2D Lookup Texture.
  96470. */
  96471. get: function () {
  96472. return this._imageProcessingConfiguration.colorGradingTexture;
  96473. },
  96474. /**
  96475. * Sets the Color Grading 2D Lookup Texture.
  96476. */
  96477. set: function (value) {
  96478. this.imageProcessingConfiguration.colorGradingTexture = value;
  96479. },
  96480. enumerable: true,
  96481. configurable: true
  96482. });
  96483. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  96484. /**
  96485. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96486. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96487. * 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;
  96488. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96489. */
  96490. get: function () {
  96491. return this.imageProcessingConfiguration.colorCurves;
  96492. },
  96493. /**
  96494. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96495. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96496. * 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;
  96497. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96498. */
  96499. set: function (value) {
  96500. this.imageProcessingConfiguration.colorCurves = value;
  96501. },
  96502. enumerable: true,
  96503. configurable: true
  96504. });
  96505. /**
  96506. * The entire material has been created in order to prevent overdraw.
  96507. * @returns false
  96508. */
  96509. BackgroundMaterial.prototype.needAlphaTesting = function () {
  96510. return true;
  96511. };
  96512. /**
  96513. * The entire material has been created in order to prevent overdraw.
  96514. * @returns true if blending is enable
  96515. */
  96516. BackgroundMaterial.prototype.needAlphaBlending = function () {
  96517. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  96518. };
  96519. /**
  96520. * Checks wether the material is ready to be rendered for a given mesh.
  96521. * @param mesh The mesh to render
  96522. * @param subMesh The submesh to check against
  96523. * @param useInstances Specify wether or not the material is used with instances
  96524. * @returns true if all the dependencies are ready (Textures, Effects...)
  96525. */
  96526. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  96527. var _this = this;
  96528. if (useInstances === void 0) { useInstances = false; }
  96529. if (subMesh.effect && this.isFrozen) {
  96530. if (this._wasPreviouslyReady) {
  96531. return true;
  96532. }
  96533. }
  96534. if (!subMesh._materialDefines) {
  96535. subMesh._materialDefines = new BackgroundMaterialDefines();
  96536. }
  96537. var scene = this.getScene();
  96538. var defines = subMesh._materialDefines;
  96539. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  96540. if (defines._renderId === scene.getRenderId()) {
  96541. return true;
  96542. }
  96543. }
  96544. var engine = scene.getEngine();
  96545. // Lights
  96546. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  96547. defines._needNormals = true;
  96548. // Textures
  96549. if (defines._areTexturesDirty) {
  96550. defines._needUVs = false;
  96551. if (scene.texturesEnabled) {
  96552. if (scene.getEngine().getCaps().textureLOD) {
  96553. defines.TEXTURELODSUPPORT = true;
  96554. }
  96555. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96556. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  96557. return false;
  96558. }
  96559. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  96560. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  96561. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  96562. defines.OPACITYFRESNEL = this._opacityFresnel;
  96563. }
  96564. else {
  96565. defines.DIFFUSE = false;
  96566. defines.DIFFUSEHASALPHA = false;
  96567. defines.GAMMADIFFUSE = false;
  96568. defines.OPACITYFRESNEL = false;
  96569. }
  96570. var reflectionTexture = this._reflectionTexture;
  96571. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96572. if (!reflectionTexture.isReadyOrNotBlocking()) {
  96573. return false;
  96574. }
  96575. defines.REFLECTION = true;
  96576. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  96577. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  96578. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  96579. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  96580. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  96581. defines.REFLECTIONBGR = this.switchToBGR;
  96582. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  96583. defines.INVERTCUBICMAP = true;
  96584. }
  96585. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  96586. switch (reflectionTexture.coordinatesMode) {
  96587. case BABYLON.Texture.EXPLICIT_MODE:
  96588. defines.REFLECTIONMAP_EXPLICIT = true;
  96589. break;
  96590. case BABYLON.Texture.PLANAR_MODE:
  96591. defines.REFLECTIONMAP_PLANAR = true;
  96592. break;
  96593. case BABYLON.Texture.PROJECTION_MODE:
  96594. defines.REFLECTIONMAP_PROJECTION = true;
  96595. break;
  96596. case BABYLON.Texture.SKYBOX_MODE:
  96597. defines.REFLECTIONMAP_SKYBOX = true;
  96598. break;
  96599. case BABYLON.Texture.SPHERICAL_MODE:
  96600. defines.REFLECTIONMAP_SPHERICAL = true;
  96601. break;
  96602. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  96603. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  96604. break;
  96605. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  96606. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  96607. break;
  96608. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  96609. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  96610. break;
  96611. case BABYLON.Texture.CUBIC_MODE:
  96612. case BABYLON.Texture.INVCUBIC_MODE:
  96613. default:
  96614. defines.REFLECTIONMAP_CUBIC = true;
  96615. break;
  96616. }
  96617. if (this.reflectionFresnel) {
  96618. defines.REFLECTIONFRESNEL = true;
  96619. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  96620. this._reflectionControls.x = this.reflectionAmount;
  96621. this._reflectionControls.y = this.reflectionReflectance0;
  96622. this._reflectionControls.z = this.reflectionReflectance90;
  96623. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  96624. }
  96625. else {
  96626. defines.REFLECTIONFRESNEL = false;
  96627. defines.REFLECTIONFALLOFF = false;
  96628. }
  96629. }
  96630. else {
  96631. defines.REFLECTION = false;
  96632. defines.REFLECTIONFRESNEL = false;
  96633. defines.REFLECTIONFALLOFF = false;
  96634. defines.REFLECTIONBLUR = false;
  96635. defines.REFLECTIONMAP_3D = false;
  96636. defines.REFLECTIONMAP_SPHERICAL = false;
  96637. defines.REFLECTIONMAP_PLANAR = false;
  96638. defines.REFLECTIONMAP_CUBIC = false;
  96639. defines.REFLECTIONMAP_PROJECTION = false;
  96640. defines.REFLECTIONMAP_SKYBOX = false;
  96641. defines.REFLECTIONMAP_EXPLICIT = false;
  96642. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96643. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96644. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96645. defines.INVERTCUBICMAP = false;
  96646. defines.REFLECTIONMAP_OPPOSITEZ = false;
  96647. defines.LODINREFLECTIONALPHA = false;
  96648. defines.GAMMAREFLECTION = false;
  96649. }
  96650. }
  96651. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  96652. defines.USERGBCOLOR = this._useRGBColor;
  96653. defines.NOISE = this._enableNoise;
  96654. }
  96655. if (defines._areLightsDirty) {
  96656. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  96657. }
  96658. if (defines._areImageProcessingDirty) {
  96659. if (!this._imageProcessingConfiguration.isReady()) {
  96660. return false;
  96661. }
  96662. this._imageProcessingConfiguration.prepareDefines(defines);
  96663. }
  96664. // Misc.
  96665. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  96666. // Values that need to be evaluated on every frame
  96667. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  96668. // Attribs
  96669. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  96670. if (mesh) {
  96671. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  96672. mesh.createNormals(true);
  96673. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  96674. }
  96675. }
  96676. }
  96677. // Get correct effect
  96678. if (defines.isDirty) {
  96679. defines.markAsProcessed();
  96680. scene.resetCachedMaterial();
  96681. // Fallbacks
  96682. var fallbacks = new BABYLON.EffectFallbacks();
  96683. if (defines.FOG) {
  96684. fallbacks.addFallback(0, "FOG");
  96685. }
  96686. if (defines.POINTSIZE) {
  96687. fallbacks.addFallback(1, "POINTSIZE");
  96688. }
  96689. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  96690. if (defines.NUM_BONE_INFLUENCERS > 0) {
  96691. fallbacks.addCPUSkinningFallback(0, mesh);
  96692. }
  96693. //Attributes
  96694. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96695. if (defines.NORMAL) {
  96696. attribs.push(BABYLON.VertexBuffer.NormalKind);
  96697. }
  96698. if (defines.UV1) {
  96699. attribs.push(BABYLON.VertexBuffer.UVKind);
  96700. }
  96701. if (defines.UV2) {
  96702. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96703. }
  96704. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  96705. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  96706. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  96707. "vFogInfos", "vFogColor", "pointSize",
  96708. "vClipPlane", "mBones",
  96709. "vPrimaryColor", "vPrimaryColorShadow",
  96710. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  96711. "shadowLevel", "alpha",
  96712. "vBackgroundCenter", "vReflectionControl",
  96713. "vDiffuseInfos", "diffuseMatrix",
  96714. ];
  96715. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  96716. var uniformBuffers = ["Material", "Scene"];
  96717. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  96718. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  96719. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  96720. uniformsNames: uniforms,
  96721. uniformBuffersNames: uniformBuffers,
  96722. samplers: samplers,
  96723. defines: defines,
  96724. maxSimultaneousLights: this._maxSimultaneousLights
  96725. });
  96726. var onCompiled = function (effect) {
  96727. if (_this.onCompiled) {
  96728. _this.onCompiled(effect);
  96729. }
  96730. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  96731. };
  96732. var join = defines.toString();
  96733. subMesh.setEffect(scene.getEngine().createEffect("background", {
  96734. attributes: attribs,
  96735. uniformsNames: uniforms,
  96736. uniformBuffersNames: uniformBuffers,
  96737. samplers: samplers,
  96738. defines: join,
  96739. fallbacks: fallbacks,
  96740. onCompiled: onCompiled,
  96741. onError: this.onError,
  96742. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  96743. }, engine), defines);
  96744. this.buildUniformLayout();
  96745. }
  96746. if (!subMesh.effect || !subMesh.effect.isReady()) {
  96747. return false;
  96748. }
  96749. defines._renderId = scene.getRenderId();
  96750. this._wasPreviouslyReady = true;
  96751. return true;
  96752. };
  96753. /**
  96754. * Compute the primary color according to the chosen perceptual color.
  96755. */
  96756. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  96757. if (!this.__perceptualColor) {
  96758. return;
  96759. }
  96760. this._primaryColor.copyFrom(this.__perceptualColor);
  96761. // Revert gamma space.
  96762. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  96763. // Revert image processing configuration.
  96764. if (this._imageProcessingConfiguration) {
  96765. // Revert Exposure.
  96766. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  96767. }
  96768. this._computePrimaryColors();
  96769. };
  96770. /**
  96771. * Compute the highlights and shadow colors according to their chosen levels.
  96772. */
  96773. BackgroundMaterial.prototype._computePrimaryColors = function () {
  96774. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  96775. return;
  96776. }
  96777. // Find the highlight color based on the configuration.
  96778. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  96779. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  96780. // Find the shadow color based on the configuration.
  96781. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  96782. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  96783. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  96784. };
  96785. /**
  96786. * Build the uniform buffer used in the material.
  96787. */
  96788. BackgroundMaterial.prototype.buildUniformLayout = function () {
  96789. // Order is important !
  96790. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  96791. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  96792. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  96793. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  96794. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  96795. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  96796. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  96797. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  96798. this._uniformBuffer.addUniform("pointSize", 1);
  96799. this._uniformBuffer.addUniform("shadowLevel", 1);
  96800. this._uniformBuffer.addUniform("alpha", 1);
  96801. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  96802. this._uniformBuffer.addUniform("vReflectionControl", 4);
  96803. this._uniformBuffer.create();
  96804. };
  96805. /**
  96806. * Unbind the material.
  96807. */
  96808. BackgroundMaterial.prototype.unbind = function () {
  96809. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  96810. this._uniformBuffer.setTexture("diffuseSampler", null);
  96811. }
  96812. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  96813. this._uniformBuffer.setTexture("reflectionSampler", null);
  96814. }
  96815. _super.prototype.unbind.call(this);
  96816. };
  96817. /**
  96818. * Bind only the world matrix to the material.
  96819. * @param world The world matrix to bind.
  96820. */
  96821. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  96822. this._activeEffect.setMatrix("world", world);
  96823. };
  96824. /**
  96825. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  96826. * @param world The world matrix to bind.
  96827. * @param subMesh The submesh to bind for.
  96828. */
  96829. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  96830. var scene = this.getScene();
  96831. var defines = subMesh._materialDefines;
  96832. if (!defines) {
  96833. return;
  96834. }
  96835. var effect = subMesh.effect;
  96836. if (!effect) {
  96837. return;
  96838. }
  96839. this._activeEffect = effect;
  96840. // Matrices
  96841. this.bindOnlyWorldMatrix(world);
  96842. // Bones
  96843. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  96844. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  96845. if (mustRebind) {
  96846. this._uniformBuffer.bindToEffect(effect, "Material");
  96847. this.bindViewProjection(effect);
  96848. var reflectionTexture = this._reflectionTexture;
  96849. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  96850. // Texture uniforms
  96851. if (scene.texturesEnabled) {
  96852. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96853. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  96854. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  96855. }
  96856. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96857. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  96858. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  96859. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  96860. }
  96861. }
  96862. if (this.shadowLevel > 0) {
  96863. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  96864. }
  96865. this._uniformBuffer.updateFloat("alpha", this.alpha);
  96866. // Point size
  96867. if (this.pointsCloud) {
  96868. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  96869. }
  96870. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  96871. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  96872. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  96873. }
  96874. else {
  96875. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  96876. }
  96877. }
  96878. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  96879. // Textures
  96880. if (scene.texturesEnabled) {
  96881. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96882. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  96883. }
  96884. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96885. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  96886. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96887. }
  96888. else if (!defines.REFLECTIONBLUR) {
  96889. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96890. }
  96891. else {
  96892. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  96893. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  96894. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  96895. }
  96896. if (defines.REFLECTIONFRESNEL) {
  96897. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  96898. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  96899. }
  96900. }
  96901. }
  96902. // Clip plane
  96903. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  96904. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  96905. }
  96906. if (mustRebind || !this.isFrozen) {
  96907. if (scene.lightsEnabled) {
  96908. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  96909. }
  96910. // View
  96911. this.bindView(effect);
  96912. // Fog
  96913. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  96914. // image processing
  96915. this._imageProcessingConfiguration.bind(this._activeEffect);
  96916. }
  96917. this._uniformBuffer.update();
  96918. this._afterBind(mesh);
  96919. };
  96920. /**
  96921. * Dispose the material.
  96922. * @param forceDisposeEffect Force disposal of the associated effect.
  96923. * @param forceDisposeTextures Force disposal of the associated textures.
  96924. */
  96925. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  96926. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  96927. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  96928. if (forceDisposeTextures) {
  96929. if (this.diffuseTexture) {
  96930. this.diffuseTexture.dispose();
  96931. }
  96932. if (this.reflectionTexture) {
  96933. this.reflectionTexture.dispose();
  96934. }
  96935. }
  96936. this._renderTargets.dispose();
  96937. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96938. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96939. }
  96940. _super.prototype.dispose.call(this, forceDisposeEffect);
  96941. };
  96942. /**
  96943. * Clones the material.
  96944. * @param name The cloned name.
  96945. * @returns The cloned material.
  96946. */
  96947. BackgroundMaterial.prototype.clone = function (name) {
  96948. var _this = this;
  96949. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  96950. };
  96951. /**
  96952. * Serializes the current material to its JSON representation.
  96953. * @returns The JSON representation.
  96954. */
  96955. BackgroundMaterial.prototype.serialize = function () {
  96956. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96957. serializationObject.customType = "BABYLON.BackgroundMaterial";
  96958. return serializationObject;
  96959. };
  96960. /**
  96961. * Gets the class name of the material
  96962. * @returns "BackgroundMaterial"
  96963. */
  96964. BackgroundMaterial.prototype.getClassName = function () {
  96965. return "BackgroundMaterial";
  96966. };
  96967. /**
  96968. * Parse a JSON input to create back a background material.
  96969. * @param source The JSON data to parse
  96970. * @param scene The scene to create the parsed material in
  96971. * @param rootUrl The root url of the assets the material depends upon
  96972. * @returns the instantiated BackgroundMaterial.
  96973. */
  96974. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  96975. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  96976. };
  96977. /**
  96978. * Standard reflectance value at parallel view angle.
  96979. */
  96980. BackgroundMaterial.StandardReflectance0 = 0.05;
  96981. /**
  96982. * Standard reflectance value at grazing angle.
  96983. */
  96984. BackgroundMaterial.StandardReflectance90 = 0.5;
  96985. __decorate([
  96986. BABYLON.serializeAsColor3()
  96987. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  96988. __decorate([
  96989. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96990. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  96991. __decorate([
  96992. BABYLON.serializeAsColor3()
  96993. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  96994. __decorate([
  96995. BABYLON.serialize()
  96996. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  96997. __decorate([
  96998. BABYLON.serialize()
  96999. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  97000. __decorate([
  97001. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97002. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  97003. __decorate([
  97004. BABYLON.serializeAsTexture()
  97005. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  97006. __decorate([
  97007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97008. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  97009. __decorate([
  97010. BABYLON.serialize()
  97011. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  97012. __decorate([
  97013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97014. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  97015. __decorate([
  97016. BABYLON.serializeAsTexture()
  97017. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  97018. __decorate([
  97019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97020. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  97021. __decorate([
  97022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97023. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  97024. __decorate([
  97025. BABYLON.serialize()
  97026. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  97027. __decorate([
  97028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97029. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  97030. __decorate([
  97031. BABYLON.serializeAsVector3()
  97032. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  97033. __decorate([
  97034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97035. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  97036. __decorate([
  97037. BABYLON.serialize()
  97038. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  97039. __decorate([
  97040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97041. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  97042. __decorate([
  97043. BABYLON.serialize()
  97044. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  97045. __decorate([
  97046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97047. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  97048. __decorate([
  97049. BABYLON.serialize()
  97050. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  97051. __decorate([
  97052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97053. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  97054. __decorate([
  97055. BABYLON.serialize()
  97056. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  97057. __decorate([
  97058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97059. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  97060. __decorate([
  97061. BABYLON.serialize()
  97062. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  97063. __decorate([
  97064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97065. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  97066. __decorate([
  97067. BABYLON.serialize()
  97068. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  97069. __decorate([
  97070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97071. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  97072. __decorate([
  97073. BABYLON.serialize()
  97074. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  97075. __decorate([
  97076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97077. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  97078. __decorate([
  97079. BABYLON.serialize()
  97080. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  97081. __decorate([
  97082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97083. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  97084. __decorate([
  97085. BABYLON.serialize()
  97086. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  97087. __decorate([
  97088. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97089. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  97090. __decorate([
  97091. BABYLON.serializeAsImageProcessingConfiguration()
  97092. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  97093. return BackgroundMaterial;
  97094. }(BABYLON.PushMaterial));
  97095. BABYLON.BackgroundMaterial = BackgroundMaterial;
  97096. })(BABYLON || (BABYLON = {}));
  97097. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  97098. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97099. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97100. s = arguments[i];
  97101. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97102. t[p] = s[p];
  97103. }
  97104. return t;
  97105. };
  97106. var BABYLON;
  97107. (function (BABYLON) {
  97108. /**
  97109. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  97110. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  97111. * It also helps with the default setup of your imageProcessing configuration.
  97112. */
  97113. var EnvironmentHelper = /** @class */ (function () {
  97114. /**
  97115. * constructor
  97116. * @param options
  97117. * @param scene The scene to add the material to
  97118. */
  97119. function EnvironmentHelper(options, scene) {
  97120. var _this = this;
  97121. this._errorHandler = function (message, exception) {
  97122. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  97123. };
  97124. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  97125. this._scene = scene;
  97126. this.onErrorObservable = new BABYLON.Observable();
  97127. this._setupBackground();
  97128. this._setupImageProcessing();
  97129. }
  97130. /**
  97131. * Creates the default options for the helper.
  97132. */
  97133. EnvironmentHelper._getDefaultOptions = function () {
  97134. return {
  97135. createGround: true,
  97136. groundSize: 15,
  97137. groundTexture: this._groundTextureCDNUrl,
  97138. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97139. groundOpacity: 0.9,
  97140. enableGroundShadow: true,
  97141. groundShadowLevel: 0.5,
  97142. enableGroundMirror: false,
  97143. groundMirrorSizeRatio: 0.3,
  97144. groundMirrorBlurKernel: 64,
  97145. groundMirrorAmount: 1,
  97146. groundMirrorFresnelWeight: 1,
  97147. groundMirrorFallOffDistance: 0,
  97148. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  97149. groundYBias: 0.00001,
  97150. createSkybox: true,
  97151. skyboxSize: 20,
  97152. skyboxTexture: this._skyboxTextureCDNUrl,
  97153. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97154. backgroundYRotation: 0,
  97155. sizeAuto: true,
  97156. rootPosition: BABYLON.Vector3.Zero(),
  97157. setupImageProcessing: true,
  97158. environmentTexture: this._environmentTextureCDNUrl,
  97159. cameraExposure: 0.8,
  97160. cameraContrast: 1.2,
  97161. toneMappingEnabled: true,
  97162. };
  97163. };
  97164. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  97165. /**
  97166. * Gets the root mesh created by the helper.
  97167. */
  97168. get: function () {
  97169. return this._rootMesh;
  97170. },
  97171. enumerable: true,
  97172. configurable: true
  97173. });
  97174. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  97175. /**
  97176. * Gets the skybox created by the helper.
  97177. */
  97178. get: function () {
  97179. return this._skybox;
  97180. },
  97181. enumerable: true,
  97182. configurable: true
  97183. });
  97184. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  97185. /**
  97186. * Gets the skybox texture created by the helper.
  97187. */
  97188. get: function () {
  97189. return this._skyboxTexture;
  97190. },
  97191. enumerable: true,
  97192. configurable: true
  97193. });
  97194. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  97195. /**
  97196. * Gets the skybox material created by the helper.
  97197. */
  97198. get: function () {
  97199. return this._skyboxMaterial;
  97200. },
  97201. enumerable: true,
  97202. configurable: true
  97203. });
  97204. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  97205. /**
  97206. * Gets the ground mesh created by the helper.
  97207. */
  97208. get: function () {
  97209. return this._ground;
  97210. },
  97211. enumerable: true,
  97212. configurable: true
  97213. });
  97214. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  97215. /**
  97216. * Gets the ground texture created by the helper.
  97217. */
  97218. get: function () {
  97219. return this._groundTexture;
  97220. },
  97221. enumerable: true,
  97222. configurable: true
  97223. });
  97224. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  97225. /**
  97226. * Gets the ground mirror created by the helper.
  97227. */
  97228. get: function () {
  97229. return this._groundMirror;
  97230. },
  97231. enumerable: true,
  97232. configurable: true
  97233. });
  97234. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  97235. /**
  97236. * Gets the ground mirror render list to helps pushing the meshes
  97237. * you wish in the ground reflection.
  97238. */
  97239. get: function () {
  97240. if (this._groundMirror) {
  97241. return this._groundMirror.renderList;
  97242. }
  97243. return null;
  97244. },
  97245. enumerable: true,
  97246. configurable: true
  97247. });
  97248. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97249. /**
  97250. * Gets the ground material created by the helper.
  97251. */
  97252. get: function () {
  97253. return this._groundMaterial;
  97254. },
  97255. enumerable: true,
  97256. configurable: true
  97257. });
  97258. /**
  97259. * Updates the background according to the new options
  97260. * @param options
  97261. */
  97262. EnvironmentHelper.prototype.updateOptions = function (options) {
  97263. var newOptions = __assign({}, this._options, options);
  97264. if (this._ground && !newOptions.createGround) {
  97265. this._ground.dispose();
  97266. this._ground = null;
  97267. }
  97268. if (this._groundMaterial && !newOptions.createGround) {
  97269. this._groundMaterial.dispose();
  97270. this._groundMaterial = null;
  97271. }
  97272. if (this._groundTexture) {
  97273. if (this._options.groundTexture != newOptions.groundTexture) {
  97274. this._groundTexture.dispose();
  97275. this._groundTexture = null;
  97276. }
  97277. }
  97278. if (this._skybox && !newOptions.createSkybox) {
  97279. this._skybox.dispose();
  97280. this._skybox = null;
  97281. }
  97282. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97283. this._skyboxMaterial.dispose();
  97284. this._skyboxMaterial = null;
  97285. }
  97286. if (this._skyboxTexture) {
  97287. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97288. this._skyboxTexture.dispose();
  97289. this._skyboxTexture = null;
  97290. }
  97291. }
  97292. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97293. this._groundMirror.dispose();
  97294. this._groundMirror = null;
  97295. }
  97296. if (this._scene.environmentTexture) {
  97297. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97298. this._scene.environmentTexture.dispose();
  97299. }
  97300. }
  97301. this._options = newOptions;
  97302. this._setupBackground();
  97303. this._setupImageProcessing();
  97304. };
  97305. /**
  97306. * Sets the primary color of all the available elements.
  97307. * @param color the main color to affect to the ground and the background
  97308. */
  97309. EnvironmentHelper.prototype.setMainColor = function (color) {
  97310. if (this.groundMaterial) {
  97311. this.groundMaterial.primaryColor = color;
  97312. }
  97313. if (this.skyboxMaterial) {
  97314. this.skyboxMaterial.primaryColor = color;
  97315. }
  97316. if (this.groundMirror) {
  97317. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97318. }
  97319. };
  97320. /**
  97321. * Setup the image processing according to the specified options.
  97322. */
  97323. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97324. if (this._options.setupImageProcessing) {
  97325. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97326. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97327. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97328. this._setupEnvironmentTexture();
  97329. }
  97330. };
  97331. /**
  97332. * Setup the environment texture according to the specified options.
  97333. */
  97334. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  97335. if (this._scene.environmentTexture) {
  97336. return;
  97337. }
  97338. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  97339. this._scene.environmentTexture = this._options.environmentTexture;
  97340. return;
  97341. }
  97342. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  97343. this._scene.environmentTexture = environmentTexture;
  97344. };
  97345. /**
  97346. * Setup the background according to the specified options.
  97347. */
  97348. EnvironmentHelper.prototype._setupBackground = function () {
  97349. if (!this._rootMesh) {
  97350. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  97351. }
  97352. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  97353. var sceneSize = this._getSceneSize();
  97354. if (this._options.createGround) {
  97355. this._setupGround(sceneSize);
  97356. this._setupGroundMaterial();
  97357. this._setupGroundDiffuseTexture();
  97358. if (this._options.enableGroundMirror) {
  97359. this._setupGroundMirrorTexture(sceneSize);
  97360. }
  97361. this._setupMirrorInGroundMaterial();
  97362. }
  97363. if (this._options.createSkybox) {
  97364. this._setupSkybox(sceneSize);
  97365. this._setupSkyboxMaterial();
  97366. this._setupSkyboxReflectionTexture();
  97367. }
  97368. this._rootMesh.position.x = sceneSize.rootPosition.x;
  97369. this._rootMesh.position.z = sceneSize.rootPosition.z;
  97370. this._rootMesh.position.y = sceneSize.rootPosition.y;
  97371. };
  97372. /**
  97373. * Get the scene sizes according to the setup.
  97374. */
  97375. EnvironmentHelper.prototype._getSceneSize = function () {
  97376. var _this = this;
  97377. var groundSize = this._options.groundSize;
  97378. var skyboxSize = this._options.skyboxSize;
  97379. var rootPosition = this._options.rootPosition;
  97380. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  97381. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97382. }
  97383. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  97384. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  97385. });
  97386. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97387. if (this._options.sizeAuto) {
  97388. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  97389. this._scene.activeCamera.upperRadiusLimit) {
  97390. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  97391. skyboxSize = groundSize;
  97392. }
  97393. var sceneDiagonalLenght = sceneDiagonal.length();
  97394. if (sceneDiagonalLenght > groundSize) {
  97395. groundSize = sceneDiagonalLenght * 2;
  97396. skyboxSize = groundSize;
  97397. }
  97398. // 10 % bigger.
  97399. groundSize *= 1.1;
  97400. skyboxSize *= 1.5;
  97401. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  97402. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  97403. }
  97404. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97405. };
  97406. /**
  97407. * Setup the ground according to the specified options.
  97408. */
  97409. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  97410. var _this = this;
  97411. if (!this._ground) {
  97412. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  97413. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  97414. this._ground.parent = this._rootMesh;
  97415. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  97416. }
  97417. this._ground.receiveShadows = this._options.enableGroundShadow;
  97418. };
  97419. /**
  97420. * Setup the ground material according to the specified options.
  97421. */
  97422. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  97423. if (!this._groundMaterial) {
  97424. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  97425. }
  97426. this._groundMaterial.alpha = this._options.groundOpacity;
  97427. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  97428. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  97429. this._groundMaterial.primaryColor = this._options.groundColor;
  97430. this._groundMaterial.useRGBColor = false;
  97431. this._groundMaterial.enableNoise = true;
  97432. if (this._ground) {
  97433. this._ground.material = this._groundMaterial;
  97434. }
  97435. };
  97436. /**
  97437. * Setup the ground diffuse texture according to the specified options.
  97438. */
  97439. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  97440. if (!this._groundMaterial) {
  97441. return;
  97442. }
  97443. if (this._groundTexture) {
  97444. return;
  97445. }
  97446. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  97447. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  97448. return;
  97449. }
  97450. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97451. diffuseTexture.gammaSpace = false;
  97452. diffuseTexture.hasAlpha = true;
  97453. this._groundMaterial.diffuseTexture = diffuseTexture;
  97454. };
  97455. /**
  97456. * Setup the ground mirror texture according to the specified options.
  97457. */
  97458. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  97459. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97460. if (!this._groundMirror) {
  97461. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  97462. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  97463. this._groundMirror.anisotropicFilteringLevel = 1;
  97464. this._groundMirror.wrapU = wrapping;
  97465. this._groundMirror.wrapV = wrapping;
  97466. this._groundMirror.gammaSpace = false;
  97467. if (this._groundMirror.renderList) {
  97468. for (var i = 0; i < this._scene.meshes.length; i++) {
  97469. var mesh = this._scene.meshes[i];
  97470. if (mesh !== this._ground &&
  97471. mesh !== this._skybox &&
  97472. mesh !== this._rootMesh) {
  97473. this._groundMirror.renderList.push(mesh);
  97474. }
  97475. }
  97476. }
  97477. }
  97478. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  97479. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  97480. };
  97481. /**
  97482. * Setup the ground to receive the mirror texture.
  97483. */
  97484. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  97485. if (this._groundMaterial) {
  97486. this._groundMaterial.reflectionTexture = this._groundMirror;
  97487. this._groundMaterial.reflectionFresnel = true;
  97488. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  97489. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  97490. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  97491. }
  97492. };
  97493. /**
  97494. * Setup the skybox according to the specified options.
  97495. */
  97496. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  97497. var _this = this;
  97498. if (!this._skybox) {
  97499. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  97500. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  97501. }
  97502. this._skybox.parent = this._rootMesh;
  97503. };
  97504. /**
  97505. * Setup the skybox material according to the specified options.
  97506. */
  97507. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  97508. if (!this._skybox) {
  97509. return;
  97510. }
  97511. if (!this._skyboxMaterial) {
  97512. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  97513. }
  97514. this._skyboxMaterial.useRGBColor = false;
  97515. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  97516. this._skyboxMaterial.enableNoise = true;
  97517. this._skybox.material = this._skyboxMaterial;
  97518. };
  97519. /**
  97520. * Setup the skybox reflection texture according to the specified options.
  97521. */
  97522. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  97523. if (!this._skyboxMaterial) {
  97524. return;
  97525. }
  97526. if (this._skyboxTexture) {
  97527. return;
  97528. }
  97529. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  97530. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  97531. return;
  97532. }
  97533. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97534. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  97535. this._skyboxTexture.gammaSpace = false;
  97536. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  97537. };
  97538. /**
  97539. * Dispose all the elements created by the Helper.
  97540. */
  97541. EnvironmentHelper.prototype.dispose = function () {
  97542. if (this._groundMaterial) {
  97543. this._groundMaterial.dispose(true, true);
  97544. }
  97545. if (this._skyboxMaterial) {
  97546. this._skyboxMaterial.dispose(true, true);
  97547. }
  97548. this._rootMesh.dispose(false);
  97549. };
  97550. /**
  97551. * Default ground texture URL.
  97552. */
  97553. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  97554. /**
  97555. * Default skybox texture URL.
  97556. */
  97557. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  97558. /**
  97559. * Default environment texture URL.
  97560. */
  97561. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  97562. return EnvironmentHelper;
  97563. }());
  97564. BABYLON.EnvironmentHelper = EnvironmentHelper;
  97565. })(BABYLON || (BABYLON = {}));
  97566. //# sourceMappingURL=babylon.environmentHelper.js.map
  97567. var BABYLON;
  97568. (function (BABYLON) {
  97569. /**
  97570. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  97571. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  97572. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  97573. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  97574. */
  97575. var VideoDome = /** @class */ (function (_super) {
  97576. __extends(VideoDome, _super);
  97577. /**
  97578. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  97579. * @param name Element's name, child elements will append suffixes for their own names.
  97580. * @param urlsOrVideo
  97581. * @param options An object containing optional or exposed sub element properties:
  97582. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  97583. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  97584. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  97585. * @param options **loop=true** Automatically loop video on end.
  97586. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  97587. */
  97588. function VideoDome(name, urlsOrVideo, options, scene) {
  97589. var _this = _super.call(this, name, scene) || this;
  97590. // set defaults and manage values
  97591. name = name || "videoDome";
  97592. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  97593. options.clickToPlay = Boolean(options.clickToPlay);
  97594. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  97595. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  97596. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  97597. // create
  97598. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  97599. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  97600. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  97601. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  97602. flat: false,
  97603. radius: options.size,
  97604. subdivisions: options.resolution,
  97605. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  97606. }, scene);
  97607. // configure material
  97608. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  97609. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  97610. material.reflectionTexture = _this._videoTexture;
  97611. material.useEquirectangularFOV = true;
  97612. material.fovMultiplier = 1.0;
  97613. // configure mesh
  97614. _this._mesh.material = material;
  97615. _this._mesh.parent = _this;
  97616. // optional configuration
  97617. if (options.clickToPlay) {
  97618. scene.onPointerUp = function () {
  97619. _this._videoTexture.video.play();
  97620. };
  97621. }
  97622. return _this;
  97623. }
  97624. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  97625. /**
  97626. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97627. * Also see the options.resolution property.
  97628. */
  97629. get: function () {
  97630. return this._material.fovMultiplier;
  97631. },
  97632. set: function (value) {
  97633. this._material.fovMultiplier = value;
  97634. },
  97635. enumerable: true,
  97636. configurable: true
  97637. });
  97638. /**
  97639. * Releases resources associated with this node.
  97640. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  97641. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  97642. */
  97643. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  97644. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  97645. this._videoTexture.dispose();
  97646. this._mesh.dispose();
  97647. this._material.dispose();
  97648. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  97649. };
  97650. return VideoDome;
  97651. }(BABYLON.Node));
  97652. BABYLON.VideoDome = VideoDome;
  97653. })(BABYLON || (BABYLON = {}));
  97654. //# sourceMappingURL=babylon.videoDome.js.map
  97655. 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\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-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*=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;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\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}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#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;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\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\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\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,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"};
  97656. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","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};"};
  97657. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  97658. globalObject["BABYLON"] = BABYLON;
  97659. //backwards compatibility
  97660. if(typeof earcut !== 'undefined') {
  97661. globalObject["Earcut"] = {
  97662. earcut: earcut
  97663. };
  97664. }
  97665. return BABYLON;
  97666. });